Development Experience: A Summary of the methods and differences between AFN and ASI, afnasi

Source: Internet
Author: User

Development Experience: A Summary of the methods and differences between AFN and ASI, afnasi

After years of iOS development, I would like to summarize the experiences of using the two network processing third-party frameworks under the HTTP protocol.

First, let's talk about AFNetworking:

1. 2 Management Objects
1. AFHTTPRequestOperationManager
* Encapsulation of NSURLConnection

2. AFHTTPSessionManager
* PairNSURLSessionEncapsulation

II,AFHTTPRequestOperationManagerSpecific Use
1. Create a manager
AFHTTPRequestOperationManager \*mgr = [AFHTTPRequestOperationManager manager];

2. encapsulate Request Parameters

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

3. Send a request

NSString * url = @ "http: // localhost: 8080/LWServer/login"; [mgr POST: url parameters: params success: ^ (AFHTTPRequestOperation \ * operation, id responseObject) {// call this block NSLog when the request is successful (@ "request succeeded --- % @", responseObject);} failure: ^ (AFHTTPRequestOperation \ * operation, NSError * error) {// call this block NSLog when the request fails (@ "request failed") ;}]; // GET request [mgr GET: url parameters: params success: ^ (AFHTTPRequestOperation \ * operation, id responseObject) {// call this block NSLog when the request is successful (@ "request succeeded --- % @", responseObject);} failure: ^ (AFHTTPRequestOperation \ * operation, NSError * error) {// call this block NSLog (@ "request failed") when the request fails;}];

Iii. parsing the data returned by the server
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 the resolution method for the data returned by the server
1> parse as JSON (default practice)
*mgr.responseSerializer = [AFJSONResponseSerializer serializer];
*responseObjectIsNSDictionaryOrNSArray

2> parse as XML
*mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
*responseObjectIsNSXMLParser

3> directly return data
* Indicates that AFN should not parse the data returned by the server and keep the original data.
*mgr.responseSerializer = [AFHTTPResponseSerializer serializer];

3. Note
* The data returned by the server must be consistent with responseSerializer.
1> the server returns JSON data.
*AFJSONResponseSerializer
*AFHTTPResponseSerializer

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

3> the server returns other data.
*AFHTTPResponseSerializer

The second is asi-http-request:

1. Two objects for sending the request
1. Send a GET request:ASIHttpRequest

2. Send a POST request:ASIFormDataRequest
* Set parameters

// The same key corresponds to only one parameter value. It is applicable to common "Single-value Parameters"-(void) setPostValue :( id <NSObject>) value forKey :( NSString \*) key // the same key (same parameter name) corresponds to multiple parameter values, applicable to "multi-value Parameters"-(void) addPostValue :( id <NSObject>) value forKey :( NSString \ *) key

Ii. Send requests
1. synchronous request
*startSynchronous

2. asynchronous request
*startAsynchronous

3. Process of listening for requests
1. How to monitor the request process
1> act as a proxy, follow<ASIHTTPRequestDelegate>Protocol to implement the proxy 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> become a proxy and do not comply<ASIHTTPRequestDelegate>Protocol, custom proxy method

request.delegate = self;[request setDidStartSelector:@selector(start:)];[request setDidFinishSelector:@selector(finish:)];

3> set block

[request setStartedBlock:^{    NSLog(@"setStartedBlock");}];[request setHeadersReceivedBlock:^(NSDictionary *responseHeaders) {    NSLog(@"setHeadersReceivedBlock--%@", responseHeaders);}];[request setDataReceivedBlock:^(NSData *data) {    NSLog(@"setDataReceivedBlock--%@", data);}];[request setCompletionBlock:^{    NSLog(@"setCompletionBlock");}];[request setFailedBlock:^{    NSLog(@"setFailedBlock");}];

2. Listener usage instructions
* If both block and proxy methods are set, both block and proxy methods are called during the request process.
* General call sequence: proxy method> block

3. If the following proxy method is implementedresponseData\responseStringNo value

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

Iv. File Download
1. Normal download
1> set the File Download path

request.downloadDestinationPath = filepath;

2> set the proxy for the Progress listener (it is best to keep it as the proxy for the Progress listener)<ASIProgressDelegate>Protocol)

request.downloadProgressDelegate = self.progressView;

2. resumable download)
1> set the temporary path for File Download

request.temporaryFileDownloadPath = tempFilepath;

2> supports resumable upload.

request.allowResumeForFileDownloads = 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 automatically identifies the MIMEType of the file. [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 (for example, the image data obtained after the photo is taken)

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

VI,ASIHttpRequestCommon usage
1. Request timeout

@property (atomic, assign) NSTimeInterval timeOutSeconds;

2. Get error information

@property (atomic, retain) NSError *error;

3. Get Response Data

// Status code @ property (atomic, assign, readonly) int responseStatusCode; // status information @ property (atomic, retain, readonly) NSString * responseStatusMessage; // The specific data returned by the server (NSString format)-(NSString *) responseString; // The specific data returned by the server (NSData format)-(NSData *) responseData;
The last is the key content, which is also a frequently asked question during the interview. The difference between the two is as follows:

I. Underlying implementation
1> the underlying layer of AFN is based on OCNSURLConnectionAndNSURLSession
2> the bottom layer of ASI is based on the pure C LanguageCFNetworkFramework
3> The Running Performance of ASI is higher than that of AFN.

2. process the data returned by the server
1> ASI does not directly provide a method for processing data on the server. It directly returns data \ string
2> AFN provides a variety of server data processing methods
* JSON Processing
* XML Processing
* Other Processing

3. Process of listening for requests
1> AFN providessuccessAndfailureThe process of listening for requests using two blocks (only successful and failed requests can be monitored)
*success: Called after the request is successful
*failure: Called upon request failure

2> ASI provides three solutions, each of which can monitor the entire request process.
(Start of listening Request, receive response header information, receive specific data, accept completed, request failed)
* Act as a proxy, observe the agreement, and implement the proxy method in the Protocol
* Become a proxy, do not comply with the Protocol, and customize the proxy method
* Set block

Iv. ease of use during file downloads and uploads
1> AFN
* It is not easy to monitor the download progress and upload progress.
* Resumable upload is not easy.
* Generally, it is only used to download small files.

2> ASI
* Download and upload are very easy.
* It is very easy to monitor the download progress and upload progress.
* Resumable upload is very easy.
* You can download large or small files.

5. ASI provides more practical functions
1> do you want to transfer the control circle during the request process?
2> you can easily set the dependencies between requests: each request isNSOperationObject
3> all requests can be managed in a unified manner.ASINetworkQueueTo manage all the request objects)
* Pause \ recover \ cancel all requests
* Listen to the download progress and upload progress of all requests in the entire queue

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.