我正在尝试构建一个很好的功能来访问网络以获取图像,如果在网络上找到它们,我会将它们存储在我制作的缓存系统中。
如果图像已经存储在缓存中,我将其返回。
该函数称为 getImageFromCache
并返回一个图像(如果它在缓存中),否则它会去网络获取。
代码可能是这样的:
UIImageView* backgroundTiles = [[UIImageView alloc] initWithImage[self getImageFromCache:@"http://www.example.com/1.jpg"]];
现在,由于网络流量导致的大延迟,我正在转向使用线程。所以我希望图像在从网络上获取结果之前显示临时图像。
我想知道的是,我如何跟踪如此多的按顺序访问并通过此函数 (getImageFromCache) 添加到 UIImageView
的图像。
有些东西在那里行不通:
-(UIImage*)getImageFromCache:(NSString*)forURL{
__block NSError* error = nil;
__block NSData *imageData;
__block UIImage* tmpImage;
if(forURL==nil) return nil;
if(![self.imagesCache objectForKey:forURL])
{
// Setting a temporary image until we start getting results
tmpImage = [UIImage imageNamed:@"noimage.png"];
NSURL *imageURL = [NSURL URLWithString:forURL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
imageData = [NSData dataWithContentsOfURL:imageURL options:NSDataReadingUncached error:&error];
if(imageData)
{
NSLog(@"Thread fetching image URL:%@",imageURL);
dispatch_async(dispatch_get_main_queue(), ^{
tmpImage = [UIImage imageWithData:imageData];
if(tmpImage)
{
[imagesCache setObject:tmpImage forKey:forURL];
}
else
// Couldn't build an image of this data, probably bad URL
[imagesCache setObject:[UIImage imageNamed:@"imageNotFound.png"] forKey:forURL];
});
}
else
// Couldn't build an image of this data, probably bad URL
[imagesCache setObject:[UIImage imageNamed:@"imageNotFound.png"] forKey:forURL];
});
}
else
return [imagesCache objectForKey:forURL];
return tmpImage;
}
最佳答案
这不是您问题的直接答案,但您是否知道无需使用 GCD 异步下载内容(在后台线程上)?只需使用 NSURLConnection 及其委托(delegate)方法。您的所有代码都将在主线程上,但实际的连接和下载将在后台进行。
(事实上,我已经编写了一个类 MyDownloader,它会为您处理所有这一切:
http://www.apeth.com/iOSBook/ch37.html#_http_requests
向下滚动到关于 MyDownloader 及其子类 MyImageDownloader 的部分,完全您需要在此处完成的事情。此外,请注意该章中的后续代码显示了如何在下载完成时使用通知,提示需要这些图像的 TableView 重新加载包含图像刚刚到达的 ImageView 的行。)
关于ios - UIImages NSURL 和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16403776/