ref – http://code.tutsplus.com/tutorials/networking-with-nsurlsession-part-1–mobile-21394
http://code.tutsplus.com/tutorials/networking-with-nsurlsession-part-2–mobile-21581
1) Simple GET of data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSLog(@"ViewController.m - viewDidLoad"); NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if(!error && data) { NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"Received JSON: %@", json); } else { NSLog(@"uh oh, ERROR IS %@", [error debugDescription]); } }]; [dataTask resume]; //start the task } |
2) Downloading a file using NSURLSessionDownloadDelegate protocol
So we want to download a file. However, we want to see what percentage we are at, as well as when the file has finished downloading.
A session configuration object is nothing more than a dictionary of properties that defines how the session it is tied to behaves. A session has one session configuration object that dictates cookie, security, and cache policies, the maximum number of connections to a host, resource and network timeouts, etc.
Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.
Once a session is created and configured by a NSURLSessionConfiguration instance, the session’s configuration cannot be modified. A SessionConfiguration is immutable. If you need to modify a session’s configuration, you have to create a new session. Keep in mind that it is possible to copy a session’s configuration and modify it, but the changes have no effect on the session from which the configuration was copied.
- Use a private UIImageView to hold the image
- privately conform to NSURLSessionDownloadDelegate protocol
- Implement protocol methods
ViewController.m
1 2 3 4 5 |
#import "ViewController.h" @interface ViewController () <NSURLSessionDownloadDelegate> @property(nonatomic, strong) UIImageView * myImageView; @end |
Add the image holder to your view hierarchy
1 2 3 4 5 6 7 8 |
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 200.0f)]; [self.myImageView setBackgroundColor:[UIColor yellowColor]]; [self.view addSubview:self.myImageView]; |
Then use a NSURLSession to get a task running
Notice that we first get a default Session Configuration object. Then we pass it into the session to be used.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- (void)viewDidLoad { [super viewDidLoad]; ... ... NSLog(@"ViewController.m - viewDidLoad"); NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://cdn.tutsplus.com/mobile/uploads/2013/12/sample.jpg"]]; [downloadTask resume]; } |
Configuring a session configuration object is as simple as modifying its properties as shown in the example. We can then use the session configuration object to instantiate a session object. The session object serves as a factory for data, upload, and download tasks, with each task corresponding to a single request.
Finally, implement the protocol methods
Make sure you use the main queue, to update your image holder with the data you just downloaded.
Also, if you are to use a progress view to show updates on progress, make sure you dispatch a code block onto the main queue, so that the main thread can run the code and show it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSData *data = [NSData dataWithContentsOfURL:location]; NSLog(@"ViewController.m - FINISHED DOWNLOADING for task"); dispatch_async(dispatch_get_main_queue(), ^{ //[self.progressView setHidden:YES]; [self.myImageView 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; dispatch_async(dispatch_get_main_queue(), ^{ //[self.progressView setProgress:progress]; NSLog(@"download progress i: %f", progress); }); } |
http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http