使用AFNetworking的AFImageCache
类强制在请求中使用缓存。以下是代码示例:
//设置图片URL请求 NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"]];
UIImage *cachedImage = [[AFImageCache sharedImageCache] cachedImageForRequest:urlRequest];
if (cachedImage) {
//如果已经缓存该图像,则设置为缓存的图像
self.imageView.image = cachedImage;
} else {
//如果没有缓存图像,则使用setImageWithURLRequest
方法请求图像,并强制使用缓存
[self.imageView setImageWithURLRequst:urlRequest placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.imageView.image = image;
//将下载的图像添加到缓存
[[AFImageCache sharedImageCache] cacheImage:image forRequest:urlRequest];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error: %@", error);
} forceFromCache:YES];
}