我正在尝试构建一个很好的功能来访问网络以获取图像,如果在网络上找到它们,我会将它们存储在我制作的缓存系统中。如果图像已经存储在缓存中,我会返回它。如果图像在缓存中,则调用该函数getImageFromCache
并返回图像,否则,它将进入网络并获取。
代码可能如下所示:
UIImageView* backgroundTiles = [[UIImageView alloc] initWithImage[self getImageFromCache:@"http://www.example.com/1.jpg"]];
现在,由于网络流量的延迟很大,我将继续使用线程。所以我希望图像在我从网络上得到结果之前显示一个临时图像。
我想知道的是如何跟踪这么多被顺序访问的图像,被UIImageView
这个函数(getImageFromCache)添加到s。
有些东西在那里行不通:
-(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;
}