Afnetworking 3.0 use of detailed and source code analysis to implement the principle

Source: Internet
Author: User

AFN principles && How AFN can be implemented using the Runloop:

NSString * Requesturl =@"Http://119.254.98.136/api/v1/web/homepage"; //Afhttpsessionmanager * Manager =[[afhttpsessionmanager alloc] init];Afhttpsessionmanager * Manager =[Afhttpsessionmanager Manager]; [Manager Get:requesturl Parameters:nil Progress:nil success:^ (Nsurlsessiondatatask * _nonnull task,ID_nullable Responseobject) {NSLog (@"the request was successful! "); NSLog (@"%@", Responseobject); } Failure:^ (Nsurlsessiondatatask * _nullable task, Nserror *_nonnull Error) {NSLog (@"the request failed! "); }];

1.

-(Nsurlsessiondatatask *) GET: (NSString *) urlstring parameters: (ID) Parameters Progress: (void(^) (Nsprogress *_nonnull)) DownloadProgress Success: (void(^) (Nsurlsessiondatatask * _nonnull,ID_nullable)) Success Failure: (void(^) (Nsurlsessiondatatask * _nullable, Nserror *_nonnull)) failure{Nsurlsessiondatatask*datatask = [Self Datataskwithhttpmethod:@"GET"urlstring:urlstring                                                 Parameters:parameters Uploadprogress:nil Downloadprogress:downloadprogress su    Ccess:success Failure:failure];    [Datatask resume]; returnDatatask;}

2, if the serialization failed, the direct execution of failure block, otherwise continue 3

-(Nsurlsessiondatatask *) Datataskwithhttpmethod: (NSString *) method URLString: (NSString*) urlstring parameters: (ID) Parameters Uploadprogress: (Nullablevoid(^) (Nsprogress *uploadprogress)) Uploadprogress downloadprogress: (Nullablevoid(^) (Nsprogress *downloadprogress)) DownloadProgress Success: (void(^) (Nsurlsessiondatatask *,ID)) Success failure: (void(^) (Nsurlsessiondatatask *, Nserror *)) failure{Nserror*serializationerror =Nil; Nsmutableurlrequest*request = [Self.requestserializer requestwithmethod:method urlstring:[[nsurl urlwithstring:urlstring RelativeToURL: Self.baseurl] absolutestring] parameters:parameters error:&Serializationerror]; if(serializationerror) {if(failure) {#pragmaClang Diagnostic push#pragmaClang diagnostic ignored "-WGNU"Dispatch_async (Self.completionqueue?: Dispatch_get_main_queue (), ^{failure (nil, serializationerror); });#pragmaClang Diagnostic Pop        }        returnNil; } __block Nsurlsessiondatatask*datatask =Nil; Datatask=[self datataskwithrequest:request uploadprogress:uploadprogress downl Oadprogress:downloadprogress Completionhandler:^ (Nsurlresponse * __unused response,IDResponseobject, Nserror *error) {        if(Error) {if(failure) {failure (datatask, error); }        } Else {            if(Success) {success (Datatask, responseobject);    }        }    }]; returnDatatask;}

3.

-(Nsurlsessiondatatask *) Datataskwithrequest: (Nsurlrequest *) Request Uploadprogress: (Nullablevoid(^) (Nsprogress *uploadprogress)) Uploadprogressblock downloadprogress: (Nullablevoid(^) (Nsprogress *downloadprogress)) Downloadprogressblock Completionhandler: (Nullablevoid(^) (Nsurlresponse *response,ID_nullable Responseobject, Nserror *_nullable error)) Completionhandler {__block Nsurlsessiondatatask*datatask =Nil; Url_session_manager_create_task_safely (^{Datatask=[Self.session datataskwithrequest:request];    }); [Self adddelegatefordatatask:datatask uploadprogress:uploadprogressblock Downloadprogress:downloadprogressblock    Completionhandler:completionhandler]; returnDatatask;}

4, the callback delegate and processing block after the Datatask set request

- (void) Adddelegatefordatatask: (Nsurlsessiondatatask *) Datatask uploadprogress: (Nullablevoid(^) (Nsprogress *uploadprogress)) Uploadprogressblock downloadprogress: (Nullablevoid(^) (Nsprogress *downloadprogress)) Downloadprogressblock Completionhandler: (void(^) (Nsurlresponse *response,IDResponseobject, Nserror *error)) completionhandler{afurlsessionmanagertaskdelegate*Delegate=[[Afurlsessionmanagertaskdelegate alloc] init]; Delegate. Manager =Self ; Delegate. Completionhandler =Completionhandler; Datatask.taskdescription=Self.taskdescriptionforsessiontasks; [Self setdelegate:DelegateFortask:datatask]; Delegate. Uploadprogressblock =Uploadprogressblock; Delegate. Downloadprogressblock =Downloadprogressblock;}

#pragma clang diagnostic push#pragma clang diagnostic ignored "-wgnu"            ?: dispatch_get_ Main_queue (), ^{                failure (nil, serializationerror);            }); #pragma clang diagnostic pop

Indicates that some specific clang compilation warnings are ignored in this interval, because afnetworking is referenced by other projects as a library, so some warnings of clang can not be ignored globally, but only when needed, the author likes to use the following: symbols, So I often see the wording of ignoring-WGNU warnings.

NSURLConnectionIs the cornerstone of the foundation URL loading system. An NSURLConnection asynchronously loaded NSURLRequest object that invokes the NSURLResponse /method of Delegate NSHTTPURLResponse , which NSData is sent to the server or read from the server; delegate can also be used to process NSURLAuthenticationChallenge , redirect, or decide NSCachedURLResponse how to save Stored on the shared NSURLCache .

NSOperationis an abstract class that simulates a single computational unit, with functions such as state, priority, and dependency, which can be canceled.

AFURLConnectionOperation将两者结合,As NSOperation a subclass, you follow NSURLConnectionDelegate a method that monitors the state of the request from beginning to end and stores the intermediate states such as requests, responses, and response data.

Create AFURLConnectionOperation and arrange it in NSOperationQueue , by setting NSOperation a new property completionBlock that specifies how to handle response and response data (or errors encountered during the request) when the operation completes.

The Afnetworking 3.0 implementation is fully encapsulated based on Nsurlsessiontask, Nsurlsessiontask is the Web request API that Apple launched in IOS7. AF supports HTTPS, network data requests, file uploads, file downloads, and monitor mobile network status. Afhttpsessionmanager inherits Afurlsessionmanager to manage network requests, uses afurlrequestserialization to encapsulate network requests, Use the afurlreponseserialization response body for processing, and use Afsecuritypolicy to verify the server certificate. Support HTTPS protocol, support local certificate and server certificate to compare and verify, AF requires IOS7 or above system. AF data transfer is mainly using block and Notifacation methods.

Use the detailed

Afurlsessionmanager How to use

1. Request Server Data

2. Uploading data

3. Multi-Threaded Download data

Afhttpsessionmanager How to use

1. Post

2. Get

3. Upload

Afsecuritypolicy

After both the server and the client generate the appropriate certificate, the iOS project imports the server-side certificate save into the project. The AFN is then validated against the server's certificate in the project.

Afsecuritypolicy verify the server to ensure the security of the access server. (This involves the difference between HTTPS and HTTP, and the different authentication methods, and how the request differs.) )

Authentication Mode for certificatesAFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

    • Afsslpinningmodenone

No validation is done, as long as the server returns a certificate

    • Afsslpinningmodepublickey

Only verify the public key part, as long as the public key part of the same validation passed, the red box of the part as long as the consistent through

    • Afsslpinningmodecertificate

In addition to the public key, the other can be consistent to pass validation.

Afurlsessionmanager

Afurlsessionmanager manages all requests, session set Nsurlsessiontaskdelegate, Nsurlsessiondatadelegate, Nsurlsessiondownloaddelegate the validation of certificate legitimacy, data transfer progress detection, the successful or failed callback of the request.

Use runtime to replace suspend with Af_supend and replace resume with Af_resume to send notifications to the top when both methods are called Afnetworkingtaskdidsuspendnotification Afnetworkingtaskdidresumenotification

Afnetworking 3.0 use of detailed and source code analysis to implement the principle

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.