Last active
May 19, 2017 15:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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