本文将使用NSURLConnection、NSURLSession、AFNetWork这三种方法来完成图片的异步加载。
NSURLConnection
需要4个步骤:
1.设置请求
NSString *url = @"http://img.ipc.me/uploads/post/17031/thumb/140x100.jpg";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
2.设置连接
NSURLConnection *content = [[NSURLConnection alloc]initWithRequest:self.request delegate:self];
3.开始连接
[content start];
4.获得数据(通过NSURLConnectionDataDelegate的方法)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; {
UIImage *image = [UIImage imageWithData:data];
}
可以看到NSURLConnection在发送请求后,通过创建连接时设置的代理来获得数据。
NSURLSession
需要3个步骤:
1.设置请求(同上)
2.创建下载任务
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:self.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
UIImage *image = [UIImage imageWithData:data];
}];
3.开始任务
[task resume];
NSURLSession以任务的形式来管理请求,通过block来获得数据,与NSURLConnection相比更为便捷。
AFNetWork
AFNetWork为UIImageView添加了新的方法,能直接在一个UIImageView的实例上异步加载图片
[self.imageView setImageWithURLRequest:request placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image) {
NSLog(@"success");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error) {
NSLog(@"failure");
}];
00000004