iOS Learning-10 downloads (4) Nsurlsession session

Source: Internet
Author: User

Nsurlconnection to manage public resources such as cookies and authentication information through a global state, which cannot be resolved if two connections are required to use different resource configurations, but this problem is resolved in nsurlsession. Nsurlsession corresponds to multiple connections at the same time, the session is created by the factory method, and the same state information is used in the same session. Nsurlsession supports three sessions of the process:

    1. defaultSessionConfiguration: In-process session (the default session), use the hard disk to cache data.
    2. ephemeralSessionConfiguration: A temporary in-process session (memory) that does not store cookies, caches locally, and puts them in memory, and the data disappears when the application exits.
    3. backgroundSessionConfiguration: A background session in which a thread is opened in the background for network data processing, compared to the default session.

The following will be a file download function to demonstrate the two sessions, in this process will also use the task of the proxy method to more detailed control of the upload operation. Let's take a look at the use of the default session to download the file, the code shows how to configure the session through Nsurlsessionconfiguration, if the file download progress through the Proxy method (similar to the previous use of the Nsurlconnection proxy method, In fact, the download is not segmented, if need to be segmented with the background, while in this process can accurately control the cancellation, suspension and recovery of the task.

////VIEWCONTROLLER.M//nsurlsession Session////copyright©2016 year Asamu. All rights reserved.//#import "ViewController.h"@interfaceViewcontroller () <NSURLSessionDownloadDelegate>{Nsurlsessiondownloadtask*_downloadtask;} @property (Weak, nonatomic) Iboutlet Uitextfield*TextField, @property (weak, nonatomic) Iboutlet Uiprogressview*Progressview, @property (weak, nonatomic) Iboutlet UILabel*label; @property (Weak, nonatomic) Iboutlet UIButton*downbtn;@end@implementationViewcontroller#pragmaMark--UI Method-(void) viewdidload {[Super viewdidload]; _progressview.progress=0;}#pragmaMark button click Event-(ibaction) Download: (ID) Sender {NSString*filename =_textfield.text; NSString*URLSTR = [NSString stringWithFormat:@"Http://mr7.doubanio.com/832d52e9c3df5c13afd7243a770c094f/0/fm/song/p294_128k.mp3", filename]; Nsurl*url =[Nsurl Urlwithstring:urlstr]; //Create requestNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //Create a session//Default SessionNsurlsessionconfiguration *sessionconfiguration =[Nsurlsessionconfiguration defaultsessionconfiguration]; //Request exceeds TimeSessionconfiguration.timeoutintervalforrequest =5.0f; //is it permissible to use cellularSessionconfiguration.allowscellularaccess =true; //Create a sessionNsurlsession *session = [Nsurlsession sessionwithconfiguration:sessionconfigurationDelegate: Self delegatequeue:nil]; _downloadtask=[Session downloadtaskwithrequest:request]; [_downloadtask resume];}-(Ibaction) Cancel: (IDSender {[_downloadtask cancel]; _label.text=@"Cancel";}-(Ibaction) Suspend: (ID) Sender {[_downloadtask suspend]; _label.text=@"Suspend";}-(Ibaction) Resume: (IDSender {[_downloadtask resume];}- (void) didreceivememorywarning {[Super didreceivememorywarning];}#pragmaMark-Set the interface state-(void) Setuistatus: (int64_t) Totalbyteswritten expectedtowrite: (int64_t) totalbytesexpectedwritten{//update UI is placed on the main threadDispatch_async (Dispatch_get_main_queue (), ^{    //set the progress bar_progressview.progress = (float) Totalbyteswritten/Totalbytesexpectedwritten; if(Totalbyteswritten = =Totalbytesexpectedwritten) {_label.text=@"Finish Download"; //off the net[UIApplication sharedapplication].networkactivityindicatorvisible =NO; _downbtn.enabled=YES; }Else{_label.text=@"Downing ..."; [UIApplication sharedapplication].networkactivityindicatorvisible=YES; }    });}#pragmaMark-Download Task agent#pragmaMark Download (will be called multiple times to record the download progress)-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) Downloadtask Didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten Totalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{[self Setuistatus:totalbyteswritten expectedTowrite : Totalbytesexpectedtowrite];}#pragmaMark Download Complete-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didfinishdownloadingtourl: (Nsurl *) location{Nserror*error; //Note See the previous article, too lazy to write ... NSString *cachepath =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; NSString*savepath =[CachePath Stringbyappendingpathcomponent:_textfield.text]; NSLog (@"%@", Savepath); Nsurl*url =[Nsurl Fileurlwithpath:savepath]; [[Nsfilemanager defaultmanager]moveitematurl:location tourl:url Error:&ERROR]; if(Error) {NSLog (@"%@", error.localizeddescription); }}#pragmaMark task completed, regardless of download success-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{if(Error) {NSLog (@"%@", error.localizeddescription); }}@end

Storyboard as shown on the right:

iOS Learning-10 downloads (4) Nsurlsession session

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.