Skip to content

Instantly share code, notes, and snippets.

@emarashliev
Created January 20, 2016 17:25
Show Gist options
  • Select an option

  • Save emarashliev/c1ca76f5780162b1ebd0 to your computer and use it in GitHub Desktop.

Select an option

Save emarashliev/c1ca76f5780162b1ebd0 to your computer and use it in GitHub Desktop.
@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