Created
January 20, 2016 17:25
-
-
Save emarashliev/c1ca76f5780162b1ebd0 to your computer and use it in GitHub Desktop.
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
| @implementation UIImageView (Asynchronous) | |
| + (instancetype _Nonnull)imageViewWithURL:(NSString * _Nonnull )url { | |
| return [self imageViewWithURL:url completionHandler:nil]; | |
| } | |
| + (instancetype _Nonnull)imageViewWithURL:(NSString * _Nonnull )url | |
| completionHandler:(completionHandler _Nullable)block { | |
| UIImageView *imageView = [UIImageView new]; | |
| [imageView loadImageWithURL:url completionHandler:block]; | |
| return imageView; | |
| } | |
| - (void)loadImageWithURL:(NSString *)url { | |
| [self loadImageWithURL:url completionHandler:nil]; | |
| } | |
| - (void)loadImageWithURL:(NSString * _Nonnull )url | |
| completionHandler:(completionHandler _Nullable)block { | |
| typeof(self) __weak weakSelf = self; | |
| NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; | |
| [[[NSURLSession sharedSession] dataTaskWithRequest:request | |
| completionHandler:^(NSData * _Nullable data, | |
| NSURLResponse * _Nullable response, | |
| NSError * _Nullable error) { | |
| dispatch_async(dispatch_get_main_queue(), ^{ | |
| weakSelf.image = [UIImage imageWithData:data]; | |
| if (block != nil) { | |
| block(error); | |
| } | |
| }); | |
| }] resume]; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment