尝试回答您的主要问题“我如何将图像加载到UICollectionview
异步?”
我建议“娜塔莎·穆拉舍夫" here,这对我来说效果很好而且很简单。
If here imgURL = [allImage objectAtIndex:k];
in allImage
属性,您保留 URL 数组,然后更新您的collectionView:cellForItemAtIndexPath:
像这样的方法:
- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url = [NSURL URLWithString:[allImage objectAtIndex:indexPath]];
[self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) {
if (succeeded) {
cell.grid_image.image = [[UIImage alloc] initWithData:data];
}
}];
}
并添加方法downloadImageWithURL:completionBlock:
到您的类,它将异步加载图像并在成功下载图像时自动更新 CollectionView 中的单元格。
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
completionBlock(YES, data);
} else {
completionBlock(NO, nil);
}
}];
}
我看到您尝试在视图出现之前预加载图像,所以也许我的解决方案不是您想要的,但从您的问题来看很难说。无论如何,你也可以通过这个实现你想要的。
斯威夫特2.2Swift 中的解决方案。
public typealias ImageFetchCompletionClosure = (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void
extension String {
func fetchImage(completionHandler: (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void) {
if let imageURL = NSURL(string: self) {
NSURLSession.sharedSession().dataTaskWithURL(imageURL) { data, response, error in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
let data = data where error == nil,
let image = UIImage(data: data)
else {
if error != nil {
completionHandler(image: nil, error: error, imageURL: imageURL)
}
return
}
dispatch_sync(dispatch_get_main_queue()) { () -> Void in
completionHandler(image: image, error: nil, imageURL: imageURL)
}
}.resume()
}
}
}
使用示例:
"url_string".fetchImage { (image, error, imageURL) in
// handle different results, either image was downloaded or error received
}