Skip to content

Instantly share code, notes, and snippets.

@tobitech
Last active May 19, 2017 15:12
Show Gist options
  • Save tobitech/daf168e153f0070b6b7588bf0834f0ad to your computer and use it in GitHub Desktop.
Save tobitech/daf168e153f0070b6b7588bf0834f0ad to your computer and use it in GitHub Desktop.
This is a UIImageView Subclass that has caching support. Good for use in TableViews and CollectionViews cells
//
// CFCustomeImageView.h
//
// Created by Tobi Omotayo on 24/10/2016.
// Copyright © 2016 Tobi Omotayo. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CFCustomeImageView : UIImageView {
NSCache *imageCache;
NSString *imageUrlString;
}
- (void)loadImageUsingUrlString:(NSString *)urlString;
@end
//
// CFCustomeImageView.m
//
// Created by Tobi Omotayo on 24/10/2016.
// Copyright © 2016 Tobi Omotayo. All rights reserved.
//
#import "CFCustomeImageView.h"
@implementation CFCustomeImageView
- (void)loadImageUsingUrlString:(NSString *)urlString {
imageUrlString = urlString;
NSURL *url = [NSURL URLWithString:urlString];
self.image = nil;
UIImage *imageFromCache = [imageCache objectForKey:urlString];
if (imageFromCache) {
self.image = imageFromCache;
return;
}
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error != nil) {
NSLog(@"%@", error);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *imageToCache = [UIImage imageWithData:data];
if (imageUrlString == urlString) {
self.image = imageToCache;
}
[imageCache setObject:imageToCache forKey:urlString];
});
}] resume];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment