Development experience: A summary of the respective use methods and differences between AFN and ASI

Source: Internet
Author: User

After many years of iOS development, we summarize the experience of using the two networks to deal with the third-party framework under the HTTP protocol.

First of all, afnetworking:

One or 2 major management objects
1.AFHTTPRequestOperationManager
* Package for the Nsurlconnection

2.AFHTTPSessionManager
* The right NSURLSession package

Second, AFHTTPRequestOperationManager the specific use
1. Create a Manager
AFHTTPRequestOperationManager \*mgr = [AFHTTPRequestOperationManager manager];

2. Package Request Parameters

NSMutableDictionary \*params = [NSMutableDictionary dictionary];params[@"username"] = @"哈哈";params[@"pwd"] = @"123";

3. Sending the request

NSString *url =@ "Http://localhost:8080/LWServer/login"; [Mgr Post:url parameters:params success:^ (afhttprequestoperation \*operation,ID responseobject) {//when the request was successful call this block nslog (@ " Successful Request---%@ ", responseobject); } failure:^ (Afhttprequestoperation \*operation, nserror *error) { //request failed call this block nslog (@ " Request Failed "); }]; //GET request [Mgr Get:url parameters:params success:^ (afhttprequestoperation \*operation, Span class= "Hljs-keyword" >id responseobject) {//when the request was successful call this block nslog (@" Request succeeded---%@ ", responseobject);} failure:^ (Afhttprequestoperation \*operation , nserror *error) {//call this block nslog (@" request Failed ");}];         

Third, the analysis of the server return data
1.AFN can automatically parse the data returned by the server
* The data returned by the server is parsed as JSON by default

2. Set how the data returned by the server is parsed
1> as JSON to parse (default practice)
*mgr.responseSerializer = [AFJSONResponseSerializer serializer];
* responseObject the type is NSDictionary orNSArray

2> as XML to parse
*mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
* responseObject the type isNSXMLParser

3> Direct return to data
* Meaning: Tell AFN not to parse the data returned by the server, keep the original
*mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

3. Note
* The data returned by the server must be aligned with Responseserializer.
The 1> server is returning JSON data
*AFJSONResponseSerializer
*AFHTTPResponseSerializer

The 2> server returns the XML data
*AFXMLParserResponseSerializer
*AFHTTPResponseSerializer

3> the server is returning additional data
*AFHTTPResponseSerializer

Next is asi-http-request:

One, 2 objects to send the request
1. Send a GET request:ASIHttpRequest

2. Send the POST request:ASIFormDataRequest
* Set parameters

// 同一个key只对应1个参数值,适用于普通“单值参数”- (void)setPostValue:(id <NSObject>)value forKey:(NSString \*)key// 同一个key(同一个参数名),会对应多个参数值,适用于“多值参数”- (void)addPostValue:(id <NSObject>)value forKey:(NSString \*)key

Second, send the request
1. Sync requests
*startSynchronous

2. Asynchronous requests
*startAsynchronous

Third, the process of monitoring the request
1. How to listen to the request process
1> as the agent, abide by the <ASIHTTPRequestDelegate> protocol, implement the Agent method in the Protocol

request.delegate = self;- (void)requestStarted:(ASIHTTPRequest *)request;- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;- (void)requestFinished:(ASIHTTPRequest *)request;- (void)requestFailed:(ASIHTTPRequest *)request;

2> becomes an agent, does not comply with <ASIHTTPRequestDelegate> the protocol, and customizes the proxy method

setDidStartSelector:@selector(start:)];[request setDidFinishSelector:@selector(finish:)];

3> setting block

[request setstartedblock:^{NSLog (@ " Setstartedblock ");}] nsdictionary *responseheaders) {NSLog (@" setheadersreceivedblock--%@ ", responseheaders) nsdata *data) {NSLog (@ " setdatareceivedblock--%@ ", data) ^{NSLog (@ "Setcompletionblock");}] ^{NSLog (@ "Setfailedblock");}]              

2. Attention to the use of monitoring
* If the block is set and the proxy method is implemented, the block and proxy methods will be called during the request.
* General Invocation Order: Proxy method > Block

3. If the following proxy method is implemented, then responseData\responseString there is no value

- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;

Iv. File Download
1. General Downloads
1> Setting the Save path for file download

request.downloadDestinationPath = filepath;

2> set the agent for progress monitoring (to be a progress listener, it is best to follow the <ASIProgressDelegate> protocol)

self.progressView;

2. Breakpoint Download (the breakpoint continues to pass)
1> setting a temporary path for file downloads

request.temporaryFileDownloadPath = tempFilepath;

2> set support for breakpoint continuation

YES;

V. File upload (set file parameters)
1. If you know the file path, it is best to use this method (because it is simple)

// ASI内部会自动识别文件的MIMEType[request setFile:file forKey:@"file"];[request addFile:file forKey:@"file"];[request setFile:file withFileName:@"basic.pptx" andContentType:@"application/vnd.openxmlformats-officedocument.presentationml.presentation" forKey:@"file"];// .....

2. If the file data is generated dynamically, use this method (such as the picture data obtained after the photo is taken)

setData:data withFileName:@"test.png" andContentType:@"image/png" forKey:@"file"];

Vi. ASIHttpRequest Common Uses of
1. Request timed out

@property (atomic, assign) NSTimeInterval timeOutSeconds;

2. Get the error message

@property (atomic, retain) NSError *error;

3. Get Response data

// 状态码@property (atomic, assign,readonly) int responseStatusCode;// 状态信息@property (atomic, retain,readonly) NSString *responseStatusMessage;// 服务器返回的具体数据(NSString格式)- (NSString *)responseString;// 服务器返回的具体数据(NSData格式)- (NSData *)responseData;
Finally, the key content, but also the interview often ask questions, the difference between the two:

First, the bottom realization
1> AFN is based on OC NSURLConnection andNSURLSession
2> ASI's underlying framework based on the Pure C language CFNetwork
3> ASI has a higher operating performance than AFN

Ii. data processing for the return of the server
1> ASI does not provide direct data processing to the server, directly returning data\string
2> AFN provides a variety of ways to process server data
* JSON processing
* XML processing
* Other processing

Third, the process of monitoring the request
1> AFN provides success failure two blocks to listen for requests (only for success and failure)
* success : Call after successful request
* failure : Call after request failed

The 2> ASI offers 3 solutions, each of which listens to the complete process of the request.
(Listener requests Start, receive response header information, receive specific data, accept, request failed)
* Become an agent, abide by the agreement, implement the agent method in the Agreement
* Become an agent, do not comply with the protocol, custom proxy methods
* Set block

Iv. Ease of use in file downloads and file uploads
1> AFN
* Not easy to listen to download progress and upload progress
* Not easy to implement a breakpoint continuation
* Generally only used to download a small file

2> ASI
* Very easy to download and upload
* Very easy to listen to download progress and upload progress
* Very easy to implement the breakpoint continued to pass
* Download or large or small files are OK

Five, ASI provides more practical functions
1> Control Circle do not relay in the request process
2> can easily set dependencies between requests: Each request is an NSOperation object
3> can manage all requests uniformly (also specifically providing a call ASINetworkQueue to manage all request objects)
* Pause \ Resume \ Cancel all requests
* Monitor the download progress and upload progress of all requests in the entire queue

Development experience: A summary of the respective use methods and differences between AFN and ASI

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.