Data Request
1. Obtain the URLSession singleton object, create a dataTask using this object, and use struct callback.
This code captures the JSON array from the website and parses it into an OC dictionary.
NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.soulghost.com/randompk/storeTest/baseRandom.php?type=attack"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];NSLog(@"%@",dict);}];
2. Enable the task
All tasks are paused during creation and should be started manually.
[task resume];
Large File Download
Large files often need to get the progress, which requires setting a proxy instead of using block callback.
1. Follow the proxy method to create two members, one for pointing to the download task object and the other for saving the breakpoint data.
@interface ViewController () <NSURLSessionDownloadDelegate>@property (nonatomic, strong) NSURLSessionDownloadTask *task;@property (nonatomic, strong) NSData *resumeData;@end
2. Obtain the URLSession singleton and create a download task. Note that the method used is different from the previous one.
- Do not forget to save the task.
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://127.0.0.1/lesson1/nav.dmg"] ];[task resume];_task = task;
3. During the download process, the following proxy method is called to indicate the number of bytes for this download, the total number of bytes for download and the total number of bytes.
-(Void) URLSession :( NSURLSession *) session downloadTask :( callback *) downloadTask didWriteData :( int64_t) bytesWritten failed :( int64_t) transaction :( int64_t) Transaction {NSLog (@ "Write volume: % lld download progress: % f ", bytesWritten, (double) totalBytesWritten/totalBytesExpectedToWrite );}
4. Call back the following proxy method after the download is complete and move the file from it. If you want to get the suggestedFilename of the response body response, you must use downloadTask.
-(Void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask usage :( NSURL *) location {NSString * path = [callback (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // you can use the recommended file name, which is the same as NSString * file = [path stringByAppendingPathComponent: downloadTask. response. suggestedFilename]; // move the NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtPath: location. path toPath: file error: nil]; [self. btn setTitle: @ "Start" forState: UIControlStateNormal];}
5. If you want to pause the download, call the following method to get the breakpoint data through the callback structure and save it in the member we created earlier for restoration.
- Use weakSelf to avoid circular references.
- The task becomes invalid after it is completed. You should point the pointer to nil to release the memory.
_ Weak typeof (self) weakSelf = self; [self. task cancelByProducingResumeData: ^ (NSData * resumeData) {// resumeData contains the starting position weakSelf for the next download. resumeData = resumeData; weakSelf. task = nil;}];
6. To restore the downloaded data, you only need to create a task through the breakpoint.
NSURLSession * session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self resume: [NSOperationQueue mainQueue]; // input the data returned from the last pause download task * task = [session resume: self. resumeData]; [task resume]; _ task = task; _ resumeData = nil;