IOS nsurlsession Implementation Network request-File download-upload-Background download

Source: Internet
Author: User


* Session NsurlsessionNsurlconnection to manage public resources such as cookies and authentication information through a global state, if two connections need to use different resource configurations, they cannot be resolved.
This problem can be solved in nsurlsession, nsurlsession simultaneously corresponds to multiple connections, the session is created by the factory method, the same state information is used in the same session, Nsurlsession supports three sessions of the process:
1. Defaultsessionconfiguration: In-process session (default session), used for hard disk to cache data.
2. Ephemeralsessionconfiguration: Temporary in-process session (memory), does not store cookies, caches to local, only in memory, and the data disappears when the application exits
3. Backgroundsessionconfiguration: Background session, compared to the default session, the session will open a county in the background for network data processing

Precise control of task cancellations, hangs, restores

1. Request Data

<span style= "FONT-SIZE:18PX;" > #pragma mark---requested data request---session----sessiondatatask-(void) loaddata{//1. Create a URL nsstring *urlstring    = [nsstring stringwithformat:@ "url"]; URLString = [URLString stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset    Urlqueryallowedcharacterset]];    Nsurl *url = [Nsurl urlwithstring:urlstring]; 2.    Create request Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; 3.        Create a session (using singleton initialization, start a task) nsurlsession *session = [Nsurlsession sharedsession]; Session creation Task Nsurlsessiondatatask *datatask = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nullable Data, Nsurlresponse * _nullable response, Nserror * _nullable error) {if (!error) {NSString *d            ATASTR = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];        NSLog (@ "%@", datastr);        } else {NSLog (@ "error is%@", error.localizeddescription);     }            }];   Resume thread, start task [Datatask resume];} </span>

2. File Upload

<span style= "FONT-SIZE:18PX;" > #pragma mark-----file upload-(void) updatafile{/** * File upload requires the Content-type type to be set in the request header, URL encoding must be used, Applicati     On/x-www-form-urlencoded: The default value, before sending all sent data URL encoding, support browser access, usually text content submission commonly used this way.     Multipart/form-data: Multi-part form data that supports browser access, does not encode anything, and is typically used for file transfers (where binary data is passed).     Text/plain: Plain Text data type, support browser access, the space before sending is replaced with "+", but not special characters encoded.     Application/json:json data type, browser access is not supported.          Text/xml:xml data type, browser access is not supported. Multipart/form-data must be set, *///1.    Create URL NSString *urlstr = @ "url";    URLSTR = [Urlstr stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset URLQueryAllowedCharacterSet]];    Nsurl *url = [Nsurl urlwithstring:urlstr]; 2.    Create request Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Set the requested as POST request.        HttpMethod = @ "POST";    3. Build the data to be uploaded nsstring *path = [[NSBundle mainbundle] pathforresource:@ "123" oftype:@ "123"];        NSData *data = [NSData Datawithcontentsoffile:path]; Set the request'sBody request.        Httpbody = data; Setup request Content-length [request setvalue:[nsstring stringwithformat:@ "%lu", (unsigned long) data.length] Forhttpheaderf    ield:@ "Content-length"]; Set Request Content-type [request setvalue:[nsstring stringwithformat:@ "multipart/form-data; boundary=%@" @ "Xia"]        forhttpheaderfield:@ "Content-type"]; 4.    Create session Nsurlsession *session = [Nsurlsession sharedsession]; Nsurlsessionuploadtask *uploadtask = [Session uploadtaskwithrequest:request fromdata:data completionHandler:^ (NSData         * _nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {if (!error) {//upload succeeded        }else {//upload failed, print error message NSLog (@ "Error---%@", error.localizeddescription);    }    }];    Resume thread start task [Uploadtask resume]; }</span>

3. File Download

<span style= "FONT-SIZE:18PX;" > #pragma mark---file download/** * In the process of downloading files using nsurlsessiondownloadtask Note: Download the file will be automatically saved to a temporary directory, you need to re-put the file in the other specified directory */-(void    ) downloadfile{//1. Create URL nsstring *urlstr =[nsstring stringwithformat:@ "%@", @ "url"];    URLSTR = [Urlstr stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset URLQueryAllowedCharacterSet]];        Nsurl *url = [Nsurl urlwithstring:urlstr];        Create request Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];        Create session Nsurlsession *session = [Nsurlsession sharedsession]; Nsurlsessiondownloadtask *downloadtask = [Session downloadtaskwithrequest:request completionhandler:^ (NSURL * _ Nullable location, Nsurlresponse * _nullable response, Nserror * _nullable error) {if (!error) {//download as            Work//Note location is the temporary save path after download, it needs to be moved to the place where it needs to be saved Nserror *saveerror; Create a custom storage path nsstring *cachepath = [Nssearchpathfordirectoriesindomains (NSCAchesdirectory, Nsuserdomainmask, YES) lastobject];            NSString *savepath = [CachePath stringbyappendingpathcomponent:@ "FileName"];                        Nsurl *saveurl = [Nsurl Fileurlwithpath:savepath];            The file is copied to the cache path [[Nsfilemanager Defaultmanager] copyitematurl:location tourl:saveurl error:&saveerror];            if (!saveerror) {NSLog (@ "Save succeeded");            } else {NSLog (@ "error is%@", saveerror.localizeddescription);        }} else {NSLog (@ "error is:%@", error.localizeddescription);    }    }];    Resume thread, start task [Downloadtask resume]; }</span>

4. File Cancel download, hang, continue to download

<span style= "FONT-SIZE:18PX;" > #pragma mark-Cancel download-(void) cancledownload{    [_downloadtask cancel];} #pragma mark---pending download-(void) suspenddownload{    [_downloadtask suspend];} #pragma mark----Resume download-(void) resumedownload{    [_downloadtask resume];    } </span>

5. Proxy method for Nsurlsession


<span style= "FONT-SIZE:18PX;" > #pragma mark----downloadtask Agent method//The download process will be called multiple times, recording the download Progress-(void) Urlsession: (Nsurlsession *) session Downloadtask: ( Nsurlsessiondownloadtask *) Downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten totalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{//Record download progress}//download complete-(void) URLSession :(Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didfinishdownloadingtourl: (NSURL *)    location{Nserror *error;    NSString *cachepath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];        NSString *savepath = [CachePath stringbyappendingpathcomponent:@ "Savename"];    Nsurl *saveurl = [Nsurl Fileurlwithpath:savepath];    Copying files via file management [[Nsfilemanager Defaultmanager] copyitematurl:location tourl:saveurl error:&error];    if (Error) {NSLog (@ "error is%@", error.localizeddescription); }}//the proxy method that is triggered when the call resumes the download [_downloadtask resume]-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes{} #pragma mark---Task completed, whether or not Load succeeded-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) error{}# Pragma mark---session background download done (local notification or update UI)-(void) Urlsessiondidfinisheventsforbackgroundurlsession: (        Nsurlsession *) session{appdelegate *appdelgate = (appdelegate *) [uiapplication sharedapplication].delegate; if (Appdelgate.backgroundsessioncompletionhandler) {void (^completionhandle) () = Appdelgate.backgroundsessioncompl        Etionhandler;        Appdelgate.backgroundsessioncompletionhandler = nil;    Completionhandle (); }}</span>

6. Background download


Nsurlsession Support Program background download and upload, Apple officially called the process outside of the upload and download, these tasks are handed to the daemon thread to complete, not the application itself, timely files in the download and upload process crashes can also continue to run (if the user forcibly shut down the program, Nsurlsession will be disconnected)
*
* In order to improve the user experience, the progress bar will always refresh the progress during the download process.
When the program into the background, the fact that the task is assigned to the iOS system to dispatch, when the specific download is not known,
If the download is complete, the file download progress should be in 100 position, because the program has been unable to update the program UI in the background,
The UI update is now done through the application proxy (Appdelegate) method


After several tasks are opened in the background, the system calls the application's nsurlsession after several other tasks have been completed.

-(void) Application: (UIApplication *) application handleeventsforbackgroundurlsession: (NSString *) identifier


Completionhandler: (void (^) ()) Completionhandler Proxy method

This method contains a Competionhandler (this action means that all the processing work is done in the app), and usually we save this object,

Until the last task is completed, the session ID (set in sessionconfig) is re-located to find the appropriate session and call Nsurlsession's

-(void) Urlsessiondidfinisheventsforbackgroundurlsession: (Nsurlsession *) session proxy method, which in this method can usually

Make UI updates and call Completionhandler to notify the system that it has done all the work


<span style= "FONT-SIZE:18PX;" > #pragma mark---background download-(void) Application: (UIApplication *) application handleeventsforbackgroundurlsession: ( NSString *) identifier Completionhandler: (void (^) ()) completionhandler{    Self.backgroundsessioncompletionhandler = Completionhandler;} -(void) Urlsessiondidfinisheventsforbackgroundurlsession: (nsurlsession *) session{    appdelegate *appdelgate = ( Appdelegate *) [uiapplication sharedapplication].delegate;        if (appdelgate.backgroundsessioncompletionhandler) {        void (^completionhandle) () = Appdelgate.backgroundsessioncompletionhandler;        Appdelgate.backgroundsessioncompletionhandler = nil;        Completionhandle ();    }} </span>





IOS nsurlsession Implementation Network request-File download-upload-Background download

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.