IOS Development Network Details (II.)

Source: Internet
Author: User
Tags tmp folder uikit

Nsurlsesstion

Nsurlconnection in IOS2 appeared, in IOS9 was announced abandoned, Nsurlsession from 13 to the present, finally ushered in its unrivaled lake era. Nsurlsession is Apple after iOS7 for HTTP data transmission of a series of interfaces, more powerful than nsurlconnection, pit less, easy to use. Today from the perspective of usage.

With Nsurlsession, fly is divided into two steps: The first step is to create a task with an instance of Nsurlsession the second part executes the task since there are tasks in both steps, let's talk about it. Nsurlsessiontask can be easily understood as tasks such as data request task, download task, upload task and so on. We are using his subclasses: Nsurlsessiontask (abstract Class) Nsurlsessiondatatasknsurlsessionuploadtasknsurlsessiondownloadtask from the names of these sub-categories, you can probably guess what they do. Next we start with different types of tasks, To use the session.
Nsurlsessiondatatask is literally a data-related task, but in fact Datatask is perfectly capable of downloadtask and Uploadtask's work. This may also be the type of task that we use the most. Simple GET requests if the requested data is relatively simple, there is no need to do some complicated operations on the returned data. Then we can use the block//shortcut to get the Session object Nsurlsession *session = [ Nsurlsession sharedsession]; Nsurl *url = [Nsurl urlwithstring:@ "Http://www.daka.com/login?username=daka&pwd=123 "];//Initializes a task through a URL, and the returned data can be processed directly inside the block nsurlsessiontask *task = [Session datataskwithurl: URL    completionhandler:^ (nsdata *data, nsurlresponse *response, nserror error) { NSLog (@ "%@", [nsjsonserialization jsonobjectwithdata:data options:kniloptions Error:nil]);}];/ /Start task [task resume]; Tips: All types of tasks call the Resume method to start a request.
Simple POST Request The difference between post and get is the request, so the POST request with the session is the same as the get process, and the difference is in the processing of the request. Nsurl *url = [Nsurl urlwithstring:@ "Http://www.daka.com/login"]; Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; request. HttpMethod = @ "POST"; request. Httpbody = [@ ' Username=daka &pwd=123 "datausingencoding:nsutf8stringencoding]; Nsurlsession *session = [nsurlsession sharedsession ];//because you want to first process the request, We initialize Tasknsurlsessiontask by request *task = [session datataskwithrequest : Request completionhandler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {NSL OG (@ "%@", [nsjsonserialization jsonobjectwithdata:data options:kniloptions Error:nil]); }]; [Task resume]; Nsurlsessiondatadelegate Proxy Method
The  nsurlsessiondatadelegate Proxy method Nsurlsession provides a convenient way for the block to process the returned data, but if you want to do further processing in the process of receiving the data, you can still invoke the relevant protocol method. Nsurlsession Proxy method and nsurlconnection some similar, are divided into receive response, receive data, request complete several stages.//The Proxy method needs to be set, but the delegate property of the session is read-only, To set up an agent only in this way create sessionnsurlsession *session = [Nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration                                                 Defaultsessionconfiguration] Delegate:self Delegatequeue:[[nsoperationqueue Alloc] init]];//Create a task (because you want to use the proxy method, you do not need to initialize the block mode) Nsurlsessiondatata SK *task = [session datataskwithrequest:[nsurlrequest requestwithurl:[nsurl urlwithstring:@ "http://www.daka.com/ Login?username=daka&pwd=123 the]]];//startup task [Task resume];//corresponds to the proxy method as follows://1. Response received from the server-(void) Urlsession: (Nsurlsession *) session Datatask: ( Nsurlsessiondatatask *) datatask didreceiveresponse:(nsurlresponse *) Response Completionhandler: (void (^) ( nsurlsessionresponsedisposition)) Completionhandler {//Allow processing of the server's response before continuing to receive the data returned by the server Completionhandler ( Nsurlsessionresponseallow);} 2. Data received from the server (may be called multiple times)-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) Datatask  Didreceivedata:(NSData *) data {//processing each received}//3. Request succeeded or failed (if failed, error has value)-(void) Urlsession: (Nsurlsession *) Session Task: (Nsurlsessiontask *) Task didcompletewitherror:(Nserror *) error {//request complete, successful or failed processing}
Simple DownloadNsurlsessiondownloadtask also provides methods for initializing and using block callbacks in two ways, Nsurl and nsurlrequest. The following is an example of Nsurl initialization: surlsession *session = [ Nsurlsession Sharedsession]; Nsurl *url = [Nsurl urlwithstring:@ "Http://www.daka.com/resources/image/icon.png"]; Nsurlsessiondownloadtask *task = [Session Downloadtaskwithurl:url completionhandler:^ (Nsurl *location, NSURLResponse * Response, Nserror *error) {//location is a temporary URL under the TMP folder in the sandbox, the file will be downloaded to this position, because the files in TMP may be deleted at any time, so we need to move the downloaded file to the desired place NSS Tring *path = [[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) Lastobject]    StringByAppendingPathComponent:response.suggestedFilename];    Cut file [[[Nsfilemanager Defaultmanager] moveitematurl:location tourl:[nsurl Fileurlwithpath:path] error:nil];}]; Start task [task resume];Simple UploadNsurlsessionuploadtask *task =[[nsurlsession Sharedsession] Uploadtaskwithrequest:request Fromfile:filename completionhandler:^ (NSData *data, Nsurlresponse *response, NS                   Error *error) {}]; and [Self.session uploadtaskwithrequest:request fromdata:body completionhandler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {NSLog (@ "-------%@", [nsjsonserialization Jsonobjectwithdata:data options:kniloptions Error:nil]); }];

Breakpoint Continuation

Other in addition, the task itself has the following methods-(void) suspend;-(void) resume;-(void) Cancel;suspend can let the current task suspend the Resume method not only can start the task, You can also wake up the suspend-state task Cancel method to cancel the current task, or you can send a cancel message to a task that is in the suspend state, and the task cannot revert to its previous state if it is canceled.

Nsurlsessionconfiguration, simply put, is the session configuration information. Such as: nsurlsessionconfiguration *config = [nsurlsessionconfiguration defaultsessionconfiguration];//Timeout config.timeoutintervalforrequest = 10;//Whether cellular network is allowed (background transfer not applicable) Config.allowscellularaccess = yes;//There are a lot of properties that can be set. The configuration we use is the default: [Nsurlsessionconfiguration Defaultsessionconfiguration], in fact, its configuration has three types: + (Nsurlsessionconfiguration *) defaultsessionconfiguration;+ ( Nsurlsessionconfiguration *) ephemeralsessionconfiguration;+ (nsurlsessionconfiguration *) Backgroundsessionconfigurationwithidentifier: (NSString *) identifier represents the nsurlsession of several different modes of operation. The default configuration stores the cache on disk, The second transient session mode does not create a cache of persistent storage, and a third background session mode allows the program to upload and download work in the background. In addition to support for task pauses and breakpoint continuation, I think the greatest improvement of nsurlsession to nsurlconnection is to support the background upload download task, which is another topic that can be discussed in depth. But I haven't done any in-depth research on this, but I'll post it later.

Asi

Sync Request:

Initiating a synchronous request synchronization means that the thread is blocked, and using this method in the main thread causes the app to hang without responding to any user events. Therefore, in application design, most are used in specialized sub-threads to increase the user experience, or to use asynchronous requests instead (as described below). -(Ibaction) Graburl: (ID) sender{  nsurl *url = [Nsurl urlwithstring:@ "http://allseeing-i.com"];  ASIHTTPRequest *request = [ASIHTTPRequest requestwithurl:url];  startsynchronous];  Nserror *error = [request ERROR];  if (!error) {    NSString *response = [request responsestring];}  }

Asynchronous Request:

The benefit of creating an asynchronous request asynchronous request is to not block the current thread, but slightly more complex than the synchronization request, at least two callback methods are added to get the asynchronous event. The following asynchronous request code completes the same thing:-(ibaction) Graburlinbackground: (ID) sender{   nsurl *url = [nsurl urlwithstring:@ "/http/ Allseeing-i.com "];   ASIHTTPRequest *request = [ASIHTTPRequest requestwithurl:url];   [Request setdelegate:self];   startasynchronous];} -(void) requestfinished: (ASIHTTPRequest *) request{   //Use when fetching text data   nsstring *responsestring = [ Request Responsestring];    Use when fetching binary data   nsdata *responsedata = [request ResponseData];}-(void) requestfailed: (asihttpreques T *) request{   nserror *error = [request ERROR];}

Queue Request:

The queue request provides a more granular control over the asynchronous request. For example, you can set the number of connections to synchronize requests in the queue. When the number of request instances added to the queue is greater than Maxconcurrentoperationcount, the request instance is set to wait until at least one request is completed and the dequeue is placed in the queue for execution. It also applies when we have multiple request requests executed sequentially (either in business or software) and only need to set Maxconcurrentoperationcount to "1". -(Ibaction) Graburlinthebackground: (ID) sender{if (![   Self-queue]) {[self Setqueue:[[[nsoperationqueue alloc] init] autorelease]];   } nsurl *url = [Nsurl urlwithstring:@ "http://allseeing-i.com"];   ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];   [Request Setdelegate:self];   [Request Setdidfinishselector: @selector (requestdone:)]; [Request Setdidfailselector: @selector (requestwentwrong:)];[[Self queue] addoperation:request];//queue was an nsoperationqueue}-(void) Requestdone: (ASIHTTPRequest *) request{nsstring *response = [request responsestring];}-(void) Requestwentwron G: (ASIHTTPRequest *) request{nserror *error = [request ERROR];} Create Nsoperationqueue, the task queue for the Cocoa architecture's execution Task (nsoperation). We can see through the source code of ASIHTTPRequest.h,
This class is itself a nsoperation subclass. This means that it can be placed directly in the "task queue" and executed. The above code team the queue is created and added in addition to the other code as in the previous example.

Upload:

Upload data to the server asiformdatarequest , simulate form form submission, its submission format and header will be automatically recognized. No files: application/x-www-form-urlencoded has files: multipart/form-dataasiformdatarequest *request = [ASIFormDataRequest Requestwithurl:url]; [Request setpostvalue:@ "Ben" forkey:@ "first_name"]; [Request setpostvalue:@ "Copsey" forkey:@ "last_name"]; [Request setfile:@ "/users/ben/desktop/ben.jpg" forkey:@ "photo"]; [Request Adddata:imagedata withfilename:@ "george.jpg" andcontenttype:@ "image/jpeg" forkey:@ "photos"];

Download:

1. Create the request queue:

First, create the network request queue, as follows: Asinetworkqueue   *que = [[Asinetworkqueue alloc] Init];self.networkqueue = que;[ Que release]; [Self.networkqueue Reset]; [Self.networkqueue Setshowaccurateprogress:yes]; [Self.networkqueue go];

2. Set the storage path

Initialize documents path NSString *path = [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"];// Initialize temporary file path nsstring *folderpath = [path stringbyappendingpathcomponent:@ ' temp '];//create File Manager nsfilemanager *filemanager = [ Nsfilemanager defaultmanager];//determine if the Temp folder exists bool fileexists = [FileManager fileexistsatpath:folderpath];if (! FileExists) {//If it does not exist, it is created because the folder is not automatically created when downloading [FileManager createdirectoryatpath:folderpath            Withintermediatedirectories:yes                             attributes:nil                                 Error:nil];

3. Sending the request

Here are some of the following objects: Customcell is my custom Cell,cell on the download and pause two buttons, whose tag value is the row of the cell, so here [Sendertag] is the download button's tag value, Self.downloadarray is an array object that holds the resource dictionary information to be downloaded, in which a key is a URL, and its corresponding value is our download link. These things, according to their actual needs to change can use Customcell *cell = (Customcell *) [Self.mytableview Cellforrowatindexpath:[nsindexpath Indexpathforrow:[sender tag] insection:0]; NSString *filepath = [[Self.downloadarray objectatindex:[sender tag]] objectforkey:@ "URL"]; NSLog (@ "filepath=%@", filePath);//Initial download path Nsurl *url = [nsurl urlwithstring:filepath];//set Download path asihttprequest *request = [[ASIHTTPRequest alloc] initwithurl:url];//set asihttprequest proxy request.delegate = self;//Initialize save zip file path NSString * Savepath = [path stringbyappendingpathcomponent:[nsstring stringwithformat:@ "Book_%d.zip", [Sender tag]]];// Initialize temporary file path nsstring *temppath = [path stringbyappendingpathcomponent:[nsstring stringwithformat:@ "temp/book_% D.zip.temp ", [sender tag]];//Set File save path [request setdownloaddestinationpath:savepath];//set temporary file path [request Settemporaryfiledownloadpath: TempPath];//Set the agent for the progress bar, [request setdownloadprogressdelegate:cell];//setting is whether the breakpoint download is supported [request Setallowresumeforfiledownloads: yes];//setting basic information [request Setuserinfo:[nsdictionary Dictionarywithobjectsandkeys:[nsnumber Numberwithint:[sender Tag]] , @ "BookID", Nil]];NSLog (@ "userinfo=%@", request.userinfo);//Add to Asinetworkqueue queue to download [Self.networkqueue addoperation:request];// Recover Request[request release];

 /asihttprequestdelegate, the way to get information before downloading, mainly to get the size of the download content , you can show how many bytes of download progress -(void) Request: (ASIHTTPRequest *) request  Didreceiveresponseheaders :(nsdictionary *) responseheaders {NSLog (@ "didreceiveresponseheaders-%@", [     Responseheaders valueforkey:@ "Content-length"]);    NSLog (@ "contentlength=%f", request.contentlength/1024.0/1024.0);    int bookid = [[Request.userinfo objectforkey:@ "BookID"] intvalue];    Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults]; float Tempconlen = [[Userdefaults objectforkey:[nsstring stringwithformat:@ "Book_%d_contentlength", BookID]]    Floatvalue];    NSLog (@ "tempconlen=%f", Tempconlen); If not saved, persist his content size if (Tempconlen = = 0) {//If not saved, persist his content size [userdefaults setobject:[nsnumber numberwithfloat    : request.contentlength/1024.0/1024.0] forkey:[nsstring stringwithformat:@ "Book_%d_contentlength", BookID]]; } }

Asihttprequestdelegate, when the download is complete, the method of execution-(void) requestfinished: (ASIHTTPRequest *) Request {int bookid = [[ Request.userinfo objectforkey:@ "BookID"] intvalue]; Customcell *cell = (Customcell *) [Self.mytableview Cellforrowatindexpath:[nsindexpath IndexPathForRow:bookid Insection:0]];cell.downloadcompletestatus = yes;cell.progressview.progress = 0.0; The wind continues to blow 0 Links: https://www.jianshu.com/p/c24cad69f89c Source: Jane Book copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

AF2.0

1. How to implement the request

2. Implement Nsurlconnection (IOS 6 & 7)afurlconnectionoperation– it inherits from Nsoperation and is responsible for managing nsurlconnection and implementing its delegate approach.afhttprequestoperation– it inherits from Afurlconnectionoperation and is specifically used to create HTTP requests. The main difference of 2.0 is that it can be used directly, without inheriting it, for reasons that will be explained at the serialization below.Afhttprequestoperationmanager– A common way to encapsulate HTTP requests, get/post/put/delete/patch ...
Nsurlsession (IOS 7)Afurlsessionmanager– Create and manage Nsurlsession objects, as well as tasks such as data and download/upload of this object, to implement proxy methods for objects and tasks. The nsurlsession API itself has some limitations, and afurlsessionmanager can make it better.Afhttpsessionmanager– it inherits from Afurlsessionmanager, encapsulates the common way of HTTP requests, get/post/put/delete/patch ... Overall: In order to support the latest Nsurlsession interface, the core components of the old nsurlconnection,2.0 are separated from the "network Request" and "task Processing". Afhttprequestoperationmanager and Afhttpsessionmanager provide similar functionality, and switching is easy, so porting from iOS 6 to iOS 7 is easy. The serialization, security, and reachability models that were previously tied to the afhttpclient are separated, and the models are reusable based on the Nsurlsession and Nsurlconnection APIs.

2.AFURLRequestserializtion (serialized)

Overview:

Requestserilization is the encapsulation of the probability of request in a afnetwroking in the network. Its prototype is actually nsurlrequest, the nsurlrequest for a second package, many such as the request header, request parameter formatting, multipar/form data file upload and other simplified processing. In summary, there are several advantages to using Afurlrequestserializer: 1. Automatically handles the request parameter escaping, and automatically formats the request parameters for different request methods. 2. A request for a Multipart/form-data method is implemented. 3. Automatic processing of user-agent,language and other request headers.

Use:

Afurlrequestserializtion in the AF framework is the encapsulation request for this part of the object, as a property of the Afhttpsessionmanaager is used. such as://    Request Data Parsemanager.requestserializer = [Afhttprequestserializer serializer]; Manager.requestSerializer.timeoutInterval = 30.F; If you are uploading with JSON-formatted data, use Afjsonrequestserializer: Manager.requestserializer = [Afjsonrequestserializer serializer]; The property that originally existed in the Nsurlrequest object can be used by the object, such as: [ Manager.requestserializer setvalue:@ "Application/json" forhttpheaderfield:@ "accept"];

a breakthrough in the serialization (serialization) 2.0 architecture is the serializable of request and disjunction. The flexibility of serialization allows more business logic to be added at the network level, and customization is more convenient.  <Afurlrequestserializer><Afurlresponseserializer > These two protocols, so that some of your complaints in 1.0 no longer exist.

3. Security

The security afnetworking supports SSL pinning. This is important for apps that involve sensitive data. Afsecuritypolicy– This class evaluates the security and trustworthiness of links through specific certificates and public keys. Adding a server certificate to your APP bundle can help prevent "man-in-the-middle attacks."

4.

Accessibility (reachability) Another feature that is decoupled from the afhttpclient is the accessibility of the network. Now you can use it alone, or as a property of Afhttprequestoperationmanager/afhttpsessionmanager. afnetworkreachabilitymanager– is responsible for monitoring the current network accessibility, providing appropriate callback and notifications when the accessibility of the network changes.
All of the UIKit extensions in UIKit Extension 2.0 have been isolated and enhanced. Afnetworkactivityindicatormanager: Adds a new auto start or end network indicator on the status bar. Uiimageview+afnetworking: Added the ability to crop or add filters before a picture is displayed. Uibutton+afnetworking (new): Similar to uiimageview+afnetworking, the button's background image is downloaded from the line. Uiactivityindicatorview+afnetworking (New): Automatically starts or ends based on the status of the network request. Uiprogressview+afnetworking (New): Automatically tracks the progress of a request's upload download. Uiwebview+afnetworking (NEW): Supports the progress and content conversion of network requests.

5. Integration

Use afnetworking 2.0:platform:ios in CocoaPods, ' 7.0 ' pod ' afnetworking ', ' 2.0.0 '

6. Code

Afhttprequestoperation *request = [[Afhttprequestoperation alloc] initwithrequest:urlrequest]; Request.responseserializer = [Afjsonresponseserializer serializer];//sets the queue for the callback, The default is to execute block callback Request.completionqueue = Your_request_operation_completion_queue () in Mainqueue; [Request setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, id responseobject) {         //After setting ' Completionqueue ', you can handle complex logic here         //Don't worry about block live main thread    } failure:^ (Afhttprequestoperation * Operation, Nserror *error) {}]; [Request start];

IOS Development Network Details (II.)

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.