iOS network Programming (vi) nsurlsession detailed

Source: Internet
Author: User

last night to browse the demo, see others request network data with is nsurlsession, at that time in thought here what, how not used, aroused my curiosity, so go to Baidu-Google-Official document one by one view, have a certain understanding, The original nsurlsession is iOS7 in the new network interface, it and we are familiar with the nsurlconnection is tied. find information, wrote a small demo, we can see, there is no shortage of places, you can leave a message to help me point out.
hmtrootviewcontroller.m//////Created by HMT on 14-6-7.//Copyright (c) 2014 Hu Mingtao. All rights reserved.//#import "HMTRootViewController.h" #import "HMTAppDelegate.h" @interface Hmtrootviewcontroller () @property (Nonatomic,strong) Uiimageview *imageview; @property (nonatomic,strong) Uiprogressview *progressindicator;@         Property (Nonatomic,strong) Nsurlsession *urlsession;  Normal session//@property (Nonatomic,strong) nsurlsession *backgroundsession;  Background session @property (Nonatomic,strong) Nsurlsessiondownloadtask *sessiondownloadtask;        Download Task@property (nonatomic,strong) Nsurlsessiondownloadtask *resumabletask;       Resume Download Task@property (nonatomic,strong) Nsurlsessiondownloadtask *backgroundtask;   Background download task@property (nonatomic,strong) NSData *partialdata; Download Local Data @end@implementation hmtrootviewcontroller-(ID) initwithnibname: (NSString *) Nibnameornil Bundle: (NSBundle *    ) nibbundleornil{self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil];     if (self) {   Custom initialization} return self;}        -(void) viewdidload{[Super Viewdidload];    Self.imageview = [[Uiimageview alloc] Initwithframe:cgrectmake (0, 64, 320, 300)];        [Self.view Addsubview:_imageview];    Self.progressindicator = [[Uiprogressview alloc] initwithprogressviewstyle:uiprogressviewstyledefault];    _progressindicator.frame = CGRectMake (50, 500, 220, 50);        [Self.view Addsubview:_progressindicator];    UIButton *canclebutton = [UIButton Buttonwithtype:uibuttontypesystem];    Canclebutton.frame = CGRectMake (120, 400, 40, 40);    [Canclebutton settitle:@ "Cancel" forstate:uicontrolstatenormal]; [Canclebutton addtarget:self Action: @selector (didclickcanclebuttonaction:) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:canclebutton];    UIButton *downloadbutton = [UIButton Buttonwithtype:uibuttontypesystem];    Downloadbutton.frame = CGRectMake (20, 400, 40, 40); [Downloadbutton settitle:@ "Download" forstate:uicontrolstatenormal];   [Downloadbutton addtarget:self Action: @selector (didclickdownloadbuttonaction:) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:downloadbutton];    UIButton *uploadbutton = [UIButton Buttonwithtype:uibuttontypesystem];    Uploadbutton.frame = CGRectMake (70, 400, 40, 40);    [Uploadbutton settitle:@ "upload" forstate:uicontrolstatenormal]; [Uploadbutton addtarget:self Action: @selector (didclickuploadbuttonaction:) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:uploadbutton];    UIButton *resumablebutton = [UIButton Buttonwithtype:uibuttontypesystem];    Resumablebutton.frame = CGRectMake (180, 400, 40, 40);    [Resumablebutton settitle:@ "Recovery" forstate:uicontrolstatenormal]; [Resumablebutton addtarget:self Action: @selector (didclickresuablebuttonaction:) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:resumablebutton];    UIButton *backgroundloadbutton = [UIButton Buttonwithtype:uibuttontypesystem]; BaCkgroundloadbutton.frame = CGRectMake (220, 400, 80, 40);    [Backgroundloadbutton settitle:@ "background download" forstate:uicontrolstatenormal]; [Backgroundloadbutton addtarget:self Action: @selector (didclickbackgroundbuttonaction:) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:backgroundloadbutton];  #pragma mark-if we need to use nsurlsession for data transmission we need:/** * Create a nsurlsessionconfiguration to set the working mode when Nssession is created (3 types) *     (1) General mode (default): The working mode is similar to the original nsurlconnection, can use the cached Cache,cookie, authentication.     * (2) Time mode (ephemeral): Do not use cached Cache,cookie, authentication. * (3) Background mode (background): In the background to complete the upload download, create a configuration object when you need to give a NSString ID to track the completion of the session is which one */Nsurlsessionconfigura        tion *sessionconfig = [nsurlsessionconfiguration defaultsessionconfiguration]; /** * @ Network settings: Refer to Settings in Nsurlconnection * Two ways to create (at the moment you don't know what the difference is) * (1) is to create a session based on the configuration you just created, the system creates a new ope by default Rationqueue Processing Session message * (2) can set the callback delegate (note that this callback delegate will be strongly referenced), and can set the delegate in which Operationqueue callback,If we set its * to [Nsoperationqueue Mainqueue] It is very convenient to make a callback in the main thread *///nsurlsession *session = [Nsurlsession sessionw    Ithconfiguration:sessionconfig]; Self.urlsession = [Nsurlsession sessionwithconfiguration:sessionconfig delegate:self delegateQueue:[    Nsoperationqueue Mainqueue]];    Nsurl *url = [Nsurl urlwithstring:@ "http://www.bizhiwa.com/uploads/allimg/2012-01/22021207-1-311536.jpg"];        Nsurlrequest *request = [Nsurlrequest Requestwithurl:url]; /** * Nsurlsessionuploadtask: Upload the task, will not download after the return of the results; * nsurlsessiondownloadtask: Download task; * Nsurlsessiondat     Atask: You can upload content, upload and then download.    */Self.sessiondownloadtask = [Self.urlsession downloadtaskwithrequest:request]; As with nsurlconnection, there are proxy methods there are block methods//[Session Datataskwithrequest:request completionhandler:^ (NSData *data,    Nsurlresponse *response, Nserror *error) {//}]; #pragma mark click Download-(void) Didclickdownloadbuttonaction: (UIButton *) button{//Because the task is suspended by default and requires a recovery task (perform a task) [_sessiondown LoaDtask resume];} #pragma mark Click Upload-(void) Didclickuploadbuttonaction: (UIButton *) button{//Determine if ImageView has content if (_imageview.image = = N        IL) {NSLog (@ "Image view is empty");            Return }//0. Add an indicator on the interface before uploading uiactivityindicatorview *indicator = [[Uiactivityindicatorview alloc] Initwithactivityindicatorstyle:    Uiactivityindicatorviewstylegray];    Set Location???    Cgsize size = _imageview.bounds.size;    Indicator.center = Cgpointmake (size.width/2.0, size.height/2.0);    [Self.imageview Addsubview:indicator];        [Indicator startanimating]; 1.        URL Nsurl *url = [Nsurl urlwithstring:@ "http://www.bizhiwa.com/uploads/allimg/2012-01/22021207-1-311536.jpg"]; 2. The default action for Request-I put,request is get nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachePolicy:    Nsurlrequestuseprotocolcachepolicy timeoutinterval:5.0f]; Request.        HttpMethod = @ "PUT"; Set up authentication for network requests! 1> Authorization String Nsstring *authstr = @ "admin:123456"; 2> BASE64 encoding, avoids data on the network in clear text//iOS, only provides BASE64 encoding support for NSData type of data nsdata *authdata = [Authstr datausingencoding:n    Sutf8stringencoding];    NSString *encodestr = [Authdata Base64encodedstringwithoptions:nsdatabase64encodingendlinewithcarriagereturn];    NSString *authvalue = [NSString stringwithformat:@ "Basic%@", Encodestr];        [Request Setvalue:authvalue forhttpheaderfield:@ "Authorization"]; 3.    Session nsurlsessionconfiguration *sessionconfig = [Nsurlsessionconfiguration defaultsessionconfiguration]; Nsurlsession *session = [nsurlsession sessionwithconfiguration:sessionconfig delegate:self delegateQueue:[        Nsoperationqueue Mainqueue]]; 4.    Uploadtask NSData *imagedata = uiimagejpegrepresentation (_imageview.image, 0.75); How to apply block request Nsurlsessionuploadtask *uploadtask = [session uploadtaskwithrequest:request fromdata:imagedata Complet   ionhandler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {             When the upload is complete, the data parameter is converted to a string, which is what the server returns nsstring *str = [[NSString alloc] Initwithdata:data Encodin        G:nsutf8stringencoding];        NSLog (@ "OK-%@", str);                [Nsthread sleepfortimeinterval:5.0f];            Dispatch_async (Dispatch_get_main_queue (), ^{[indicator stopanimating];                    [Indicator Removefromsuperview];            });        }]; Because the task is suspended by default, the task needs to be resumed (perform the task) [Uploadtask resume];} #pragma mark Click Cancel//Nsurlconnection once sent is not able to cancel. However, we can easily cancel out a nsurlsessiontask task-(void) Didclickcanclebuttonaction: (UIButton *) button{/** * When canceled, this urlsessio will be recalled N:task:didcompletewitherror: Agent method, notify you to update the UI in a timely manner. When a task is canceled, it is also possible to callback this proxy method again URLSession:downloadTask:didWriteData:BytesWritten:totalBytesExpectedToWrite: * Of course, D     The Idcomplete method is definitely the last callback. *///if (_sessiondownloadtask) {//////Cancel download request//[_sessiondownloadtask cancel];//_sessio Ndownloadtask = nil;//} if (!Self.sessiondownloadtask) {//Stop the download task, save the data to be recovered to a variable, to facilitate later recovery download use [Self.sessiondownloadtask Cancelby            producingresumedata:^ (NSData *resumedata) {self.partialdata = Resumedata;                    Self.sessiondownloadtask = nil;    }];                        }} #pragma mark resumes download (breakpoint continuation)-(void) Didclickresuablebuttonaction: (UIButton *) button{if (self.partialdata) {            Self.sessiondownloadtask = [Self.urlsession downloadTaskWithResumeData:self.partialData];                    Self.partialdata = nil; }else{nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://pic4.duowan.c            Om/wow/1002/130782267821/130782458426.jpg "];                Self.resumabletask = [Self.urlsession downloadtaskwithrequest:request]; } [Self.sessiondownloadtask resume];} #pragma mark background Download mode-(void) Didclickbackgroundbuttonaction: (UIButton *) button{nsurlrequest *request =[Nsurlrequest requestwithurl:[nsurl urlwithstring:@ "HTTP://DLDIR1.QQ.COM/QQFILE/QQFORMAC/QQ_V3.1.2.DMG"];        Self.backgroundtask = [[self backgroundsession] downloadtaskwithrequest:request]; [Self.backgroundtask resume];} #pragma mark-nsurlsessiondownloadtaskdelegate//Download complete-(void) Urlsession: (Nsurlsession *) session Downloadtask: ( Nsurlsessiondownloadtask *) Downloadtask Didfinishdownloadingtourl: (Nsurl *) location{/** *******->appdelegete inside     method typedef void (^myblock) ();     @property (copy, nonatomic) Myblock Backgroundurlsessioncompletionhandler; Method called at end of background request-(void) Application: (UIApplication *) application handleeventsforbackgroundurlsession: (NSString *) IDE Ntifier Completionhandler: (void (^) ()) completionhandler{Self.backgroundurlsessioncompletionhandler = CompletionH     Andler;                }///If it is a background nsurlsession, this method is called after the background request is finished, notifying you that the UI should be updated if (session = = [Self backgroundsession]) {        Self.backgroundtask = nil; HmtapPdelegate *appdelegate = (hmtappdelegate *) [uiapplication sharedapplication].delegate; if (Appdelegate.backgroundurlsessioncompletionhandler) {void (^handler) () = Appdelegate.backgroundu            Rlsessioncompletionhandler;            Appdelegate.backgroundurlsessioncompletionhandler = nil;        Handler (); }}//The cache processing here does not do well, everyone according to their own method of processing on the line, as well as the image of the store to its own URL path, so there will be no duplicate nsfilemanager *filemanager = [Nsfilema    Nager Defaultmanager];    Nsurl *cachesurlpath = [[FileManager urlsfordirectory:nscachesdirectory Indomains:nsuserdomainmask] lastObject]; According to the URL gets to the downloaded file name, stitching into the sandbox storage path (location is the temporary file directory downloaded, in the TMP folder) Nsurl *destinationpath = [Cachesurlpath        Urlbyappendingpathcomponent:[location Lastpathcomponent]];    Nserror *error = nil;    BOOL success = [FileManager moveitematurl:location tourl:destinationpath error:&error];        [FileManager removeitematurl:location Error:null]; Location is the temporary file directory that is downloaded to copy files from the Temp folder to the Sandbox//BOOLSuccess = [FileManager copyitematurl:location tourl:destinationpath error:&error];  if (success) {Dispatch_async (Dispatch_get_main_queue (), ^{UIImage *image = [UIImage            Imagewithcontentsoffile:[destinationpath Path]];            Self.imageView.image = image;                Uiimageview will automatically crop the picture to fit its frame, the following attribute is the display of the original Self.imageView.contentMode = Uiviewcontentmodescaleaspectfill;    }); }}//the Proxy Method-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) task, regardless of whether the task is successful or not Didcompletewitherror: (Nserror *) error{//If the error is nil, it proves that the download was successful, otherwise it would be necessary to query the cause of the failure. If a portion of the download is downloaded, this error contains an NSData object that can be used if the subsequent task is to be resumed (Error = = nil) {Dispatch_async (Dispatch_get_main_queue ()        , ^{Self.progressIndicator.hidden = YES;    }); }}//Transfer Progress-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didwritedata: (int64_t) Byteswritten TOTALBYTESWRItten: (int64_t) Totalbyteswritten totalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite{double    CurrentValue = Totalbyteswritten/(double) totalbytesexpectedtowrite;        Dispatch_async (Dispatch_get_main_queue (), ^{NSLog (@ "%f", CurrentValue);        Self.progressIndicator.hidden = NO;    self.progressIndicator.progress = CurrentValue; });} Unknown-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask Didresumeatoffset: (int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes{} #pragma mark- Nsurlsession Another important feature: You can continue to transfer tasks even when the app is not in the foreground. Of course, our session mode is also for the background mode-(nsurlsession *) backgroundsession{//through to the background token, we can only create a background session, so here use dispatch once block static    Nsurlsession *backgroundsession = nil;    Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{nsurlsessionconfiguration *config = [Nsurlsessionconfiguration BackgroundS essionconfiguration:@ "Com.shinobicontrols.BackgroundDownload.BacKgroundsession "];            Backgroundsession = [nsurlsession sessionwithconfiguration:config delegate:self Delegatequeue:nil];        }); return backgroundsession;}    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} /* #pragma mark-navigation//in a storyboard-based application, you'll often want to do a little preparation before Nav igation-(void) Prepareforsegue: (Uistoryboardsegue *) Segue Sender: (ID) sender{//Get The new view controller using [Segu    E Destinationviewcontroller]. Pass the selected object to the new view Controller.} */@end

@ Nice nsurlsession article
IOS 7 Series Translations: Forget Nsurlconnection, Embrace nsurlsession!



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.