A brief analysis of afnetworking packaging ideas

Source: Internet
Author: User
Tags deprecated

http://blog.csdn.net/qq_34101611/article/details/51698473

First, the development of afnetworking 1. AFN version 1.0

The basic part of AFN is Afurlconnectionoperation, a nsoperation subclass that implements Nsurlconnection-related delegate+blocks, and the network part is nsurlconnection Complete, and then use the Nsoperation State (isready→isexecuting→isfinished) changes for network control. The network request is completed on a specified thread (networkrequestthread).
Afurlconnectionoperation is a very pure network request operation, can perform start/cancel/pause/resume operation on him, can obtain corresponding nsurlrequest and Nsurlresponse data. Uploadpress and downloadprogress are provided for easy use.
Afhttprequestoperation is a subclass of afurlconnectionoperation, a layer of encapsulation for the HTTP+HTTPS protocol, such as StatusCode, Content-type, etc. Added a callback block for successful and failed requests, providing addacceptablecontenttypes: for easy use at the top level.

2. AFN version 2.0

NSURLSession
Nsurlsession is the new class introduced in IOS 7 to replace Nsurlconnection. Nsurlconnection has not been deprecated and should not (in fact, eventually be discarded) for some time to come. They have some overlap, afnetworking provides a higher level of abstraction, and maximizes its usefulness.
模块化
One of the main criticisms of afnetworking is cumbersome. Although its architecture makes it modular at the class level, its packaging does not allow for the selection of independent functions. As time went on, Afhttpclient became particularly overwhelmed. In Afnetworking 2.0, you can pick and choose the components you need through CocoaPods subspecs

3. AFN version 3.0

AFN 3.0+ deprecated nsurlconnection, providing only nsurlsession support.

Second, nsurlsession simple and practical 1. Common Get/post Requests
    1. Get URL
    2. Create requests, modify request methods, request body (GET request not required)
    3. Get Global session
    4. Initiating a task (deserialization)
    5. End Task
2. Upload Request
NSData *imagedata = uiimagepngrepresentation (image);1.NSURLNsurl *url = [Nsurl urlwithstring:@"Http://localhost/post/upload.php"];2.NSMutableURLRequest nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];2.1 Request for Change method. HttpMethod = @"POST";2.2. Set the request header, boundary this is a delimiter, can be casually written, as long as it is not ChineseNSString *contenttypevalue = [NSString stringwithformat:@"Multipart/form-data; boundary=%@ ", Kboundaryupload]; [Request Setvalue:contenttypevalue forhttpheaderfield:@"Content-type"];Nsurlsession do not put the uploaded file into the request body, should be placed in the Nsurlsession method NSData *filedata = [Self Formdatawithfiledata:imagedata serverfieldname:@ "UserFile" Filesavename:@ "abc.png"]; //3. Get system-provided nsurlsession nsurlsession *globalsession = [nsurlsession sharedSession]; //4. Upload task by session [[Globalsession uploadtaskwithrequest:request Fromdata:filedata completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, NSError * _ Nullable error) {//4. Deserialization if (error== nil && data.length>0 {id result =[nsjsonserialization jsonobjectwithdata:data options: 0 error:null]; nslog (@ "login-----%@", result);}] Resume];                
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
-(NSData *) Formdatawithfiledata: (NSData *) fileData serverfieldname: (NSString *) Serverfieldname Filesavename: ( NSString *) filesavename{1.NSMutableData nsmutabledata *datam = [Nsmutabledata data];/**-----------------------------11454065798049615451989194362 Content-disposition:form-data; Name= "UserFile"; Filename= "Abc.txt" Content-type:application/octet-stream 111222333-----------------------------1145406579804 9615451989194362--* *2. Splicing head nsmutablestring *headerstring = [nsmutablestring string];2.1 Stitching the first line [headerstring appendformat:@"--%@\r\n", kboundaryupload];2.1 Stitching the second row [headerstring appendformat:@//2.3 stitching the third row [headerstring appendstring:@ "Content-Type: Application/octet-stream\r\n\r\n "]; //2.4 turns the string of the head into binary nsdata *headerdata = [headerstring datausingencoding: Nsutf8stringencoding]; //2.5 stitching to Datam back [Datam Appenddata:headerdata]; //3. Splicing content [Datam Appenddata:filedata]; [Datam appenddata:[@ "\ r \ n" datausingencoding:nsutf8stringencoding]]; //4. Stitching tail NSString *tailstring = [NSString stringwithformat:@"--%@--\r\n\r\n ", Kboundaryupload]; [Datam appenddata:[tailstring datausingencoding:nsutf8stringencoding]; return datam.copy;}          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
3. Download request
- (NSURLSession *)downLoadSession{    if (_downLoadSession==nil) {        //开发中,就用这个        NSURLSessionConfiguration *defaultConfigration = [NSURLSessionConfiguration defaultSessionConfiguration];        /**            参数1:配置            参数2:代理            参数3:队列,如果我们写的是主队列,那么代理方法在主线程调用                    如果是通过 [[NSOperationQueue] alloc] init]那么代理方法在子线程调用                    nil 这相当于 [[NSOperationQueue] alloc] init]         */        _downLoadSession = [NSURLSession sessionWithConfiguration:defaultConfigration delegate:self delegateQueue:nil];    }    return _downLoadSession;}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *) event{//1.nsurl nsurl *url = [NSURL URLWithString:@  "Http://localhost/videos.zip"]; //2. Download us in order to set up the agent, get the progress, we create the session nsurlsession *downloadsession = self.downloadsession; //3. Initiated by downloadsession download task Nsurlsessiondownloadtask *downloadtask = [downLoadSession Downloadtaskwithurl:url]; //4.resume [Downloadtask resume];}         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
Three, AFNetworking3.0 package thinking analysis 1. The Runloop in the interior of the AFN

AFN a thread dedicated to accessing the network request, and in this method of threading, he modifies the method and dispatch_once with static, to ensure the security of this method and to open only one piece of memory space, and to ensure that his thread does not die, In this method, he calls the method of another network request entry.

In this portal method he creates a runloop and then adds a nsmachport port in order for him to have source (because the runloop with source can really run).
Then start Runloop, through the runloop in the inside of the continuous loop, constantly send messages, let him do things.

2. Nsurlsession-based encapsulation

Afhttpsessionmanager encapsulates common processing of HTTP requests, including the Get/post method, and also includes methods for parsing server response data

Get Request for Afhttpsessionmanager

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
    • 1
    • 2
    • 3
    • 4
    • 1
    • 2
    • 3
    • 4

Post request for Afhttpsessionmanager

- (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
    • 1
    • 2
    • 3
    • 4
    • 1
    • 2
    • 3
    • 4

AFN Parsing related

AFN when parsing, the JSON data is parsed by default. If you want to parse the XML data, you need to manually put responseSerializer the value of the

AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
    • 1
    • 2
    • 1
    • 2

The return value type of the method is also changed to XML and then parsed by itself.
If the server returns a normal data type, then tell AFN to parse it with ordinary data types, what the server will return, and how to parse it.

AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

A brief analysis of afnetworking packaging ideas

Related Article

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.