您可以简单地从服务器上即时加载它们,但随后需要网络连接。要从服务器异步加载它们,您可以使用以下代码:
dispatch_queue_t image_queue = dispatch_queue_create("com.company.app.imageQueue", NULL);
dispatch_queue_t main_queue = dispatch_get_main_queue();
dispatch_async(image_queue, ^{
NSString *URLString = @"http://example.com/images/19191919.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(main_queue, ^{
[imageView setImage:image];
});
});
如果你愿意,你也可以将图片保存到缓存目录(不推荐使用文档目录,因为它会与Apples iOS Data Storage Guidelines冲突)并在下载图像之前检查两次,那么代码将如下所示:
NSString *fileName = @"19191919.png";
NSString *URLBaseString = @"http://example.com/images/";
NSString *URLString = [URLBaseString stringByAppendingString:fileName];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *dataPath = [cachePath stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ( [fileManager fileExistsAtPath:dataPath] )
{
UIImage *image = [UIImage imageWithContentsOfFile:dataPath];
[imageView setImage:image];
}
else
{
dispatch_async(image_queue, ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:URLString];
UIImage *image = [UIImage imageWithData:imageData];
[UIImagePNGRepresentation(image) writeToFile:dataPath atomically:YES];
dispatch_async(main_queue, ^{
[imageView setImage:image];
});
});
}
此代码尚未经过测试,但应该可以工作。请注意,我依靠 ARC 来管理内存。