redribben

asynchronous

Oct 26th, 2014
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. - (void)doThisTask {
  2. // For this snippet we are downloading the same in two tasks.
  3. NSString *imageUrl = @"http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
  4. // You always start by creating an NSURLConfiguration.
  5. NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  6. // This creates a session using the current class as a delegate.
  7. NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig
  8.                                                       delegate:self
  9.                                                  delegateQueue:nil];
  10. //Tasks are always created by sessions. This one is created with the block-based method. Remember you could still use the NSURLSessionDownloadDelegate to track download progress.
  11. NSURLSessionDownloadTask *getImageTask = [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]
  12.                                                     completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  13.                                                         // Here you use the location variable provided in the completion handler to get a pointer to the image
  14.                                                         UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
  15.                                                         // Finally you could, for example, update UIImageView’s image to show the new file.
  16.                                                         dispatch_async(dispatch_get_main_queue(), ^{_imageWithBlock.image = downloadedImage;});
  17.                                                     }];
  18.  
  19. // You always have to start up the task!
  20. [getImageTask resume];
  21. }
Advertisement
Add Comment
Please, Sign In to add comment