Đang cố gắng để trả lời câu hỏi chính của bạn "Làm thế nào tôi có thể tải hình ảnh đến một UICollectionview
không đồng bộ?"
Tôi sẽ đề xuất giải pháp được cung cấp bởi "Natasha Murashev" here, hoạt động tốt cho tôi và thật đơn giản.
Nếu đây imgURL = [allImage objectAtIndex:k];
trong allImage
tài sản mà bạn giữ mảng các URL, sau đó cập nhật phương thức collectionView:cellForItemAtIndexPath:
của bạn như thế này:
- (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];
}
}];
}
Và thêm phương pháp downloadImageWithURL:completionBlock:
đến lớp học của bạn, mà sẽ tải hình ảnh không đồng bộ và các tế bào cập nhật trong CollectionView tự động khi hình ảnh được tải xuống thành công.
- (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);
}
}];
}
tôi thấy bạn cố gắng để tải trước hình ảnh trước khi xem xuất hiện như vậy có lẽ giải pháp của tôi không phải là những gì bạn thấy những gì, nhưng từ câu hỏi của bạn thật khó để nói. Làm thế nào, bạn có thể đạt được những gì bạn muốn với điều này là tốt.
Swift 2.2 Giải pháp trong Swift.
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()
}
}
}
mẫu Cách sử dụng:
"url_string".fetchImage { (image, error, imageURL) in
// handle different results, either image was downloaded or error received
}
gì là dùng quá lâu đặc biệt? Và hình ảnh là kích cỡ nào? – Wain
bạn nên thực hiện [[self collectionView] reloadData] này [[self collectionView] reloadData]; trong chủ đề chính. Nó không phải là một câu trả lời. Đó chỉ là bình luận. – stosha
sử dụng EGOImageView: https://github.com/enormego/EGOImageLoading –