Extend UIImageView (create a category) and use this code. Also use UIImageView+AFNetworking.
- (void)setDownloadedImage:(NSString *)imageName{
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *localImagePath = [libraryPath stringByAppendingPathComponent:imageName];
// Check if the image is already downloaded
if (![[NSFileManager defaultManager] fileExistsAtPath:localImagePath]) {
// Store image
NSURL *serverFilePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@/images/avatars/%@", SERVER_URL, imageName]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:serverFilePath];
[imageData writeToFile:localImagePath atomically:YES];
// Switch back to the main thread to update the UI
dispatch_sync(dispatch_get_main_queue(), ^{
[self setImageWithURL:[NSURL fileURLWithPath:localImagePath] placeholderImage:nil];
});
});
}
else{
[self setImageWithURL:[NSURL fileURLWithPath:localImagePath] placeholderImage:nil];
}
}
It checks if the image is already downloaded and if it is not it will be stored and read from disk. If it is already downloaded it will also read from disk.