我有一个productImageArray
,其中包含url作为数组的元素。
我正在尝试在图片视图中加载这些网址。
以下是关于我如何加载它的方式。
UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center=CGPointMake(160.0,240.0 );
spinner.hidesWhenStopped=YES;
[self.view addSubview:spinner];
[spinner startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
dispatch_sync(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
});
});
问题是,
当我使用下面的代码时,我的tableview的每个单元格都会加载图像数据但仍会冻结用户界面,直到数据完全加载为止
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
答案 0 :(得分:2)
@ Anbu.Karthik回答是对的。
但是,也许最简单的解决方案是使用SDWebImage
之类的东西?这个库将处理这个问题以及更多(缓存,错误管理,正确的tableview单元处理,......)。
我认为你应该至少花几分钟时间来看一下:https://github.com/rs/SDWebImage
修改强>
如果您使用SDWebImage
和UIActivityIndicator-for-SDWebImage
,则可以通过以下方式替换整个代码:
[self.productImage setImageWithURL:[NSURL URLWithString:productImageArray[indexPath.row]]
usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
有关UIActivityIndicator-for-SDWebImage
的更多信息:https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
答案 1 :(得分:1)
试试这个
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
dispatch_sync(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
self.productImage.image = [UIImage imageWithData:storeImageData];
});
});
或尝试
self.productImage.image = nil; //// [UIImage imageNamed:@"default.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:productImageArray[indexPath.row]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
UIImage *currentImage = [UIImage imageWithData:data];
if (currentImage) {
dispatch_async(dispatch_get_main_queue(), ^{
UITableviewCell *getCurrentCell = (id)[tableView cellForRowAtIndexPath:indexPath];
if (getCurrentCell)
self.productImage.image = currentImage;
});
}
}
}];
[task resume];
答案 2 :(得分:0)
NSString *url_Img1 = @"Your url";
Uiimageview *view_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img1]]];