Skip to content

Instantly share code, notes, and snippets.

@Shosta
Created November 2, 2017 14:58
Show Gist options
  • Save Shosta/3b2bdf55e95db40fb43db860476c1d82 to your computer and use it in GitHub Desktop.
Save Shosta/3b2bdf55e95db40fb43db860476c1d82 to your computer and use it in GitHub Desktop.
NSURLSession use in Objective-C with Delegate or with Blocks
- (void)downloadSomethingWithoutDelegate{
NSURL *url = [NSURL URLWithString:@"https://vignette.wikia.nocookie.net/vsbattles/images/4/4a/Askeladd.jpg"];
NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 4
downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
}];
//3
//[downloadTask resume];
}
- (void)downloadSomethingWithADelegate{
// Create a session
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://google.com/sample.jpg"]];
[downloadTask resume];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSData *data = [NSData dataWithContentsOfURL:location];
// To do something on the main thread, like update the UI
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setHidden:YES];
[self.imageView setImage:[UIImage imageWithData:data]];
});
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
float progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
// To do something on the main thread, like update the UI
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setProgress:progress];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment