[英]UIImage asynchronously is not loading
我想從 url 獲取圖像,我正在這樣做:
for(int i = 0; i < 50; i++)
{NSString *MyURL=[NSString stringWithFormat:@"http://*********/tatoo/%@/%@%d.png" ,@"b",@"b",i+1];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
[tmp addObject:image];
});
}
});
}
images = [[NSArray alloc]initWithArray:tmp];
Url 是 valide ,但 tmp 是空的。 任何想法這里有什么問題? 任何幫助將不勝感激!
您可以使用 AsyncImageView 加載圖像而不影響您的 UI。
從https://github.com/nicklockwood/AsyncImageView下載第三方類
AsyncImageView *storeImage = [[AsyncImageView alloc]init];
//This will load any no logo image first. If url is dead then also it will work
storeImage.image =[UIImage imageNamed:@"no-logo.png"];
NSString *UrlSTR = @"ANY_IMAGE_URL";
NSURL *imageURL = [NSURL URLWithString:UrlSTR];
storeImage.contentMode = UIViewContentModeScaleAspectFit;
storeImage.imageURL = imageURL;
這將在后台加載您的圖像。
異步下載尚未完成,您需要等待它們。
使用操作隊列或調度組等待它們全部完成,然后您就可以使用該數組。
另請注意,您無法保證數組中圖像的任何順序,因為您不知道每次下載需要多長時間。 另外,最好不要同時開始 60 次下載...
在添加圖像數據之前是否初始化了 tmp?
tmp =[NSArray alloc]init];
在 for 循環之前初始化
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.