iOS Web Development (3) using nsurlsession

Source: Internet
Author: User

    • Nsurlsession Introduction

Nsurlsession in iOS7.0 began to introduce, in the framework of the position and nsurlconnection parallel

Nsurlsession is capable of completing all nsurlconnection functions and has a very large function extension


Starting with iOS9.0, Apple officially abandoned nsurlconnection


The main classes that are involved in the use of nsurlsession are the relationships between them

650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/7C/B2/wKiom1bWdTPh9yjOAAF0FwGe7SU279.png " title= "Screen shot 2016-03-02 pm 1.08.10.png" alt= "Wkiom1bwdtph9yjoaaf0fwge7su279.png"/>


Three modes of operation:

Default session mode: Similar to nsurlconnection, using disk caching

Instantaneous session mode: Do not use disk cache

Background session mode: can also be uploaded or downloaded when the program enters the background


Nsurlsessionconfigration is used to generate the configuration for these three modes of operation, as follows

+ (Nsurlsessionconfiguration *) defaultsessionconfiguration+ (nsurlsessionconfiguration *) ephemeralsessionconfiguration+ (Nsurlsessionconfiguration *) Backgroundsessionconfigurationwithidentifier: ( NSString *) identifier


Nsurlsession the creation of the Session object:

Use the default session mode, default cache, Cookie, and credential+ (nsurlsession *) sharedsession//use the specified operating mode + (Nsurlsession *) Sessionwithconfiguration: (nsurlsessionconfiguration*) configuration//using the specified working mode, queue for Task runtime, Agent + (Nsurlsession *) Sessionwithconfiguration: (nsurlsessionconfiguration*) configuration delegate: (id<nsurlsessiondelegate>) Delegate Delegatequeue: (Nsoperationqueue *) queue


Nsurlsession to send a network request using the steps:

A. Creating a Task object

B. Controlling the execution of tasks

C. Obtaining the results of a task execution in a block or proxy method


Three types of tasks supported: (base class nsurlsessiontask for tasks)

Data tasks using Nsurlsessiondatatask description

Download tasks using Nsurlsessiondownloadtask description

Upload Task using Nsurlsessionuploadtask description



    • of the Task object

Task Object Nsurlsessiontask in Nsurlsession, all created by Nsurlsession object

Emphasis: Asynchronous operations do not block execution of the current code and cannot get results by return values or parameters

Nsurlsessiontask the status of the Task object:

@property (readonly) nsurlsessiontaskstate statetypedef ns_enum (Nsinteger, nsurlsessiontaskstate) {Nsurlsessiontasks taterunning = 0,//running Status nsurlsessiontaskstatesuspended = 1,//Pending Status Nsurlsessiontaskstatecanceling = 2,//Cancel Status nsurlsessiontaskstatecompleted = 3,//completion status};


When a task object is created, the status of the task is suspended

Methods to control task execution (modify task status):

-(void) Cancel/Cancel task-(void) resume//Run task-(void) suspend//Suspend task


    • Data task-block way to get results

Data Task creation:

-(Nsurlsessiondatatask *) Datataskwithurl: (nsurl *) URL Completionhandler: (void (^) (NSData *data, Nsurlresponse * Response, Nserror *error)) completionhandler-(Nsurlsessiondatatask *) Datataskwithrequest: (Nsurlrequest *) request Completionhandler: (void (^) (NSData *data, Nsurlresponse *response, nserror*error)) Completionhandler

The result of processing the request in the block (response data, Response object, Error object)

For example: Send a GET request to get JSON data for the specified game task information

nsstring *urlstr = @ "Http://localhost/lolShow.php?number=20&from=0"; nsurl * url = [nsurl urlwithstring:urlstr]; nsurlrequest * request = [nsurlrequest requestwithurl:url];//Create Data Task nsurlsession  * session = [nsurlsession sharedsession]; nsurlsessiondatatask * datatask = [session datataskwithrequest:request  completionhandler:^ (nsdata * __nullable data, nsurlresponse * __nullable  Response, nserror * __nullable error)  {    if  ( error  )  {        nslog (@ "1 %@", [error  Localizeddescription]);         return ;    }     //serializes JSON data into OC objects     nsarray * arr = [ Nsjsonserialization jsonobjectwithdata:data options:0 error:&error];    if  ( error )  {         nslog (@ "2 %@",  [error localizeddescription]);         return ;    }    //Dictionary Turn model     for  (nsdictionary * dict in arr )  {         AMHeroModel * model = [AMHeroModel  Heromodelwithdict:dict];        [self.heroinfoarray addobject: model];    }    [[nsoperationqueue mainqueue]  addoperationwithblock:^{        [self stoploading];//Refresh ui     }];}];/ /Start Task [datatask resume];



    • Data task-proxy method to get results

Creation of data tasks:

-(Nsurlsessiondatatask *) Datataskwithurl: (Nsurl *) url-(Nsurlsessiondatatask *) Datataskwithrequest: (NSURLRequest *) Request

Agent Properties for Nsurlsession

@property (ReadOnly, retain) id< nsurlsessiondelegate > Delegate

Agency agreements involved: <NSURLSessionDelegate><NSURLSessionTaskDelegate>

<NSURLSessionDataDelegate><NSURLSessionDownloadDelegate>


Common proxy methods for data tasks:

Received answer Object-(void) Urlsession: (Nsurlsession *) session Datatask: (nsurlsessiondatatask*) datatask Didreceiveresponse: ( Nsurlresponse *) Response Completionhandler: (void (^) (nsurlsessionresponsedisposition disposition)) completionhandler//receiving data (may execute multiple times)-(void) Urlsession: (Nsurlsession *) session Datatask: (nsurlsessiondatatask*) Datatask didreceivedata: (NSData *) data//complete a request for the answer process-(void) Urlsession: (Nsurlsession *) session task: ( Nsurlsessiontask *) Task Didcompletewitherror: (NSERROR *) error


This article is from the "Ammon" blog, make sure to keep this source http://annmeng.blog.51cto.com/3321237/1746703

iOS Web Development (3) using 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.