I have a class that I call RemoteImageHandler. Here is the .h file:
#import <UIKit/UIKit.h>
@interface RemoteImageHandler : NSObject
- (void)imageForUrl:(NSURL*)url callback:(void(^)(UIImage *image))callback;
+ (RemoteImageHandler *)shared;
@end
And the .m file:
#import "RemoteImageHandler.h"
@interface RemoteImageHandler ()
@property (nonatomic, strong) NSMutableDictionary *imageDictionary;
@end
@implementation RemoteImageHandler
- (void)imageForUrl:(NSURL*)url callback:(void(^)(UIImage *image))callback {
if (!!self.imageDictionary[url]) {
callback(self.imageDictionary[url]);
} else {
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL:url];
if (data == nil)
callback(nil);
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:data];
self.imageDictionary[url] = image;
callback(image);
});
});
}
}
+ (TQRemoteImageHandler *)shared {
static TQRemoteImageHandler *shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[self alloc] init];
});
return shared;
}
@end
In my table view, whenever I want an image from a remote location (let's say this is in cellForRowAtIndexPath, I use this:
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
[[RemoteImageHandler shared] imageForUrl:someURLCorrespondingToTheImageYouWant callback:^(UIImage *image) {
cell.imageView.image = image;
}];
return cell;
}