(7) basic usage of NSURLSession download and data acquisition, nsurlsession

Source: Internet
Author: User
Tags tmp folder

(7) basic usage of NSURLSession download and data acquisition, nsurlsession
Introduction

NSURLSession is a series of Network Interface libraries officially provided by Apple. It allows users to easily download and obtain data. In the previous article, we introduced the NSURLConnection function for downloading files and resumable data transfer, which is troublesome and cumbersome for file operations. If NSURLSession is used, all of this will become extremely easy.

Usage
  • 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];
  • Small File Download
    1. Obtain the URLSession singleton object and create a downloadTask.

    • Note that this task downloads the file to the tmp folder by default, and will delete the file in seconds if it is not processed after the download ends. The general practice is to move it to Document or Caches, after the download is complete, the struct is called and the object can be processed in the struct.
    • NSFileManager allows you to copy and move files. The callback location is the URL of the file just downloaded in tmp.

      NSURLSession * session = [NSURLSession sharedSession]; NSURLSessionDownloadTask * task = [session downloadTaskWithURL: [NSURL URLWithString: @ "http: // 127.0.0.1/lesson1/nav. dmg "] completionHandler: ^ (NSURL * location, NSURLResponse * response, NSError * error) {// temporarily download to tmp, which must be processed in a timely manner; otherwise, it will be deleted by the system in seconds. // Move the temporary file to the Caches folder NSString * path = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // you can use the recommended file name, consistent with the server NSString * file = [path stringByAppendingPathComponent: response. suggestedFilename]; // move the NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtPath: location. path toPath: file error: nil];}];

      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.

    • Note: Clear resumeData.
    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;
  • When resumable upload starts, the following proxy method is called to describe the file information.

    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.