IOS 8: "Go" afnetworking study notes

Source: Internet
Author: User

Source Address: http://fann.im/blog/2012/08/21/afnetworking-notes/

  1. This note was written at the time of AFN v0.10.1, AFN v1.0 added a lot of new things, such as SSL support, but the overall structure did not change.
  2. Follow up on an article afnetworking Notes 2

From @mattt Introduction to AFN: Everybody Loves afnetworking and so Can you!. Learn AFN, simply record it to deepen your understanding.

The basic part of the AFN is Afurlconnectionoperation, a nsoperation subclass, which implements Nsurlconnection-related delegate+blocks, and the network part is made up of Nsurlconnection is completed, and then the Nsoperation State (isready→isexecuting→isfinished) changes are used to control the network. 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. Support Nsinputstream/nsoutputstream, provide uploadpress and downloadprogress for other use.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/ip"]];AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request];operation.completionBlock = ^ {    NSLog(@"Complete: %@", operation.responseString);};[operation start];

Interstitial: @mattt in Nshipster there is a nsoperation in detail about the state of nsoperation, priority, dependency and so on, to understand afurlconnectionoperation very helpful.

Understanding the Afurlconnectionoperation and then looking at afhttprequestoperation is a lot simpler. 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, provided for addAcceptableContentTypes: easy use at the upper level.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/robots.txt"]];AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {    NSLog(@"Success: %@", operation.responseString);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {    NSLog(@"Failure: %@", error);}];[operation start];

Afjsonrequestoperation is a subclass of Afhttprequestoperation, with special handling for JSON type requests, in the afhttprequestoperation+ After the basic work of afurlconnectionoperation, Afjsonrequestoperation has been very convenient for direct use. Specifies that JSON acceptableContentTypes: responseJSON data objects that have been parsed are returned directly to support JSON. After downloading to the JSON data, the JSON data is parsed in a separate thread queue (json_request_operation_processing_queue), and the success block is recalled by the main thread after processing is complete.

AFN JSON Encode/decode processing is very clever, now has a lot of JSON parsing library, third-party Jsonkit, Sbjson, and so on, IOS 5+ comes with nsjsonserialization, different projects may vary depending on the needs of different Library, AFN encapsulates a afjsonutilities, provides AFJSONEncode and AFJSONDecode two methods to NSClassFromString NSSelectorFromString find the JSON library used in the project and then Encode/decode.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/get"]];AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {        NSLog(@"Success :%@", JSON);     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {        NSLog(@"Failure: %@", error);     }];[operation start];

Afxmlrequestoperation/afpropertylistrequestoperation/afimagerequestoperation and AFJSONRequestOperation are similar, for XML, Plist, the image type request did some processing. Where afimagerequestoperation an additional imageprocessingblock, take the picture can be in a separate thread queque image processing, such as zoom, fillet, picture effects, etc., and then handed over to Main_queue Success block.

AFN also provides a uiimageview+afnetworking category that can be used setImageWithURL: to set up images. This cagetory and sdwebimage are similar but simpler, the image download is done by AFN, and the image cache is handled by Nscache.

Directly with these already can be convenient to do network requests, AFN on these basis also provides a afhttpclient, the HTTP request Headers, user-agent and so on again packaging, easy to use. Afhttpclient is a singleton, URL encoding of the request parameters, maintenance of a nsoperationqueue, different requests to generate the respective afhttprequestoperation and then enqueueHTTPRequestOperation: Add the queue order execution; registerHTTPOperationClass: method is used to register the above json/xml/plist/image operation, to get the request results to the corresponding operation processing. Afhttpclient also makes different URL parameters and Headers processing for different requests such as Get/post/head/put/delete, including the Multipart/form-data type.

Afhttpclient Support Batch add operations, generate a batchedoperation, all operations as batchedoperation dependency, and then turn all operations and Batchedoperation are added to operationqueue so that each operation can be done with a progressblock to return the currently completed operations number and total, and so on all operations All finished will do batchedoperation Completionblock, you can do after this batch of operations to do some aftercare.

Afhttpclient advocates that the network request for the same application (same BaseURL) encapsulate its own HTTPClient subclass, which is much more convenient. Refer to Wbkhttpclient.

AFN also provides a lot of modules, can be very convenient and AFN integration to do some work, such as Oauth,amazon S3, see afnetworking-extensions.

AFN author @mattt do something very own set of ideas inside, recommended what I learned from Afnetworking's GitHub issues, video.

IOS 8: "Go" afnetworking study notes

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.