- (void)viewDidLoad
{
[super viewDidLoad];
// 下载小文件的方式
// 1.NSData dataWithContentsOfURL
// 2.NSURLConnection
}
// 1.NSData dataWithContentsOfURL
- (void)downloadFile
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 其实这就是一个GET请求
NSURL *url = [NSURL URLWithString:@"http://hd.shijue.cvidea.cn/tf/140422/2330218/5355ca2f3dfae93acb000001.JPEG"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"%lu", (unsigned long)data.length);
});
}
// 2.NSURLConnection 创建一个子线程在子线程中发送异步请求,然后再主线程中刷新界面
- (void)downloadFile2
{
NSURL *url = [NSURL URLWithString:@"http://hd.shijue.cvidea.cn/tf/140422/2330218/5355ca2f3dfae93acb000001.JPEG"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%lu", (unsigned long)data.length);
}];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self downloadFile2];
}