Skip to content

Commit

Permalink
Download image asynchronous way using a completition handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto Halgravez committed Mar 29, 2017
1 parent 202dedf commit 0a1c89a
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions Gemelas/Gemelas/AGTImageViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ @interface AGTImageViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *photoView;


@end

@implementation AGTImageViewController
Expand All @@ -39,28 +38,28 @@ - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

#pragma mark - Actions
- (IBAction)donwloadImage:(id)sender {
[self imageFromInternetWithCompletitionHandler:^(UIImage *image) {
self.photoView.image = image;
}];
}

#pragma mark - Utils
-(void)imageFromInternetWithCompletitionHandler:(void (^)(UIImage *image))completitionHandler {
//Download image in background thread
//Now best practice, use dispatch_get_global_queue to reuse a queue already available in the system
dispatch_queue_t download = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

//Create a queue
dispatch_queue_t gemelas = dispatch_queue_create("charmander", 0);

//Send to background thread
dispatch_async(gemelas, ^{
dispatch_async(download, ^{
NSURL *url = [NSURL URLWithString:@"http://kingofwallpapers.com/charmander/charmander-013.jpg"];

NSData *imageData = [NSData dataWithContentsOfURL:url];
NSData *data = [NSData dataWithContentsOfURL:url];

//Execute in main thread
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];

self.photoView.image = image;
//Execute completitonHandler
UIImage *image = [UIImage imageWithData:data];
completitionHandler(image);
});
});




}


@end

0 comments on commit 0a1c89a

Please sign in to comment.