IOS 8: "Go" afnetworking 2.0

Source: Internet
Author: User
Tags image filter uikit

Source Address: http://nshipster.cn/afnetworking-2/

Afnetworking is one of the most widely used open source projects in IOS and OS X development today. It has helped thousands of well-hailed applications and provided the foundation for other outstanding open source libraries. This project is one of the most active and influential projects in the community, with 8,700 star, 2,200 fork and 130 contributors.

In all respects, afnetworking has become almost mainstream.

but have you ever heard of its new version? afnetworking 2.0.

This week's Nshipster: An exclusive announcement of Afnetworking's future.

Disclaimer: Nshipster is written by Afnetworking's author, so this is not an objective view of afnetworking and its merits. What you can see is a personal view of the current and future versions of afnetworking.

The general idea of afnetworking

Beginning in May 2011, afnetworking as an extension of the Apple sample code in a dead LBS project, its success was due to timing. At that time ASIHTTPRequest is the mainstream of the network, and Afnetworking's core idea makes it a more modern solution that developers crave.

Nsurlconnection + nsoperation

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.

Afnetworking's first major breakthrough was to combine the two. AFURLConnectionOperationas 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.

Blocks

The block and Grand Central Dispatch introduced by IOS 4 fundamentally improved the application development process. Developers can use blocks to put together related functions, rather than using delegate to make a mess of logic in their applications. GCD can easily dispatch work back and forth without having to face messy threads, calls, and operations queues.

More importantly, for each request operation, you can customize the method by block NSURLConnectionDelegate (for example, by setWillSendRequestForAuthenticationChallengeBlock: overwriting the default connection:willSendRequestForAuthenticationChallenge: method).

Now we can create AFURLConnectionOperation and arrange it 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.

Serialization & Validation

More in-depth, the request operation operation can also be responsible for validating the HTTP status code and the content type of the server response, for example, in application/json response to MIME types, you can serialize the NSData to a JSON object.

Loading the JSON, XML, property list, or image from the server can be abstracted and likened to a potential file load operation, so that the developer can imagine the process as a promise rather than an asynchronous network connection.

Introduction Afnetworking 2.0

Afnetworking wins the balance between ease of use and scalability, but it is not without room for improvement.

In the second big version, Afnetworking was designed to eliminate the quirks of the original design while adding some powerful new architectures to next-generation IOS and OS X applications.

Motivation
    • compatible with Nsurlsession - NSURLSession is the new class introduced in IOS 7 for substitution NSURLConnection . NSURLConnectionhas not been discarded and should not be in the future, but it NSURLSession is the future of the network in Foundation, and it is a good future, because it improves many of the previous shortcomings. (Refer to WWDC Session 705 "What's New in Foundation Networking", a good overview). At first it was speculated that NSURLSession the presence of afnetworking would not be useful. But in fact, although they have some overlap, afnetworking can provide a higher level of abstraction. afnetworking 2.0 Not only does this, it also uses and expands NSURLSession to pave the way for potholes and maximizes its practicality.

    • modularity -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. Over time, AFHTTPClient it becomes particularly overwhelming (its tasks include creating requests, serializing query string parameters, determining response parsing behavior, building and managing operation, and monitoring network accessibility). in Afnetworking 2.0, you can pick and choose the components you need through CocoaPods subspecs.

Actor lineup NSURLConnectionComponent (IOS 6 & 7)
    • AFURLConnectionOperation- NSOperation a subclass that is responsible for managing NSURLConnection and implementing its Delegate method.
    • AFHTTPRequestOperation- AFURLConnectionOperation a subclass that is used to generate HTTP requests that can differentiate between acceptable and unacceptable status codes and content types. The biggest difference in version 2.0 is that you can use this class directly instead of inheriting it , for reasons that can be found in the "Serialization" section.
    • AFHTTPRequestOperationManager-wrapper class for common HTTP Web service operations, AFHTTPRequestOperation supported by NSURLConnection .
NSURLSessionComponent (IOS 7)
    • AFURLSessionManager-Create and manage classes of object-based objects, as NSURLSessionConfiguration NSURLSession well as manage session data, download/upload tasks, and delegate methods to implement the session and its associated tasks. Because of the NSURLSession strange vacancy in the API design, any and NSURLSession related code can be AFURLSessionManager improved .
    • AFHTTPSessionManager- AFURLSessionManager a subclass that wraps common HTTP Web service operations through AFURLSessionManager NSURLSession supported by.

Overall : To support the new NSURLSession APIs and the old ones that are not deprecated and useful NSURLConnection , the core components of Afnetworking 2.0 are divided into request operation and session tasks. AFHTTPRequestOperationManagerand AFHTTPSessionManager provide similar functionality, their interfaces can be relatively easy to swap when needed (such as switching between IOS 6 and 7).

All previously binding AFHTTPClient functions, such as serialization, security, and accessibility, were split into separate modules that could be used by the API based on NSURLSession and NSURLConnection .

Serialization of

Afnetworking 2.0 One of the breakthroughs in the new architecture is the use of serialization to create requests, parse responses. More business logic can be transferred to the network layer through the flexible design of serialization, and it is easier to customize the previously built-in default behavior.

    • <AFURLRequestSerializer>-Objects conforming to this protocol are used to process the request, which converts the request parameter into the form of query string or entity body, and sets the necessary header. Those of you who don't like AFHTTPClient using query string encoding parameters, you must like this.

    • <AFURLResponseSerializer>-Objects conforming to this protocol are used to validate, serialize, and correlate data into useful forms, such as JSON objects, images, and even mantle-based model objects. AFHTTPClient AFHTTPRequestOperation There is now a responseSerializer property to set the appropriate handler, compared to the endless inheritance. Again, NSURLProtocol there is no useless inspired request for the Operation class to register, and instead it's a great responseSerializer attribute. Thank God.

Security

Thanks to Dustin Barker, Oliver letterer, Kevin Harwood and others for their contributions, afnetworking now has built-in SSL pinning support, which is important for handling sensitive information applications.

    • AFSecurityPolicy-The evaluation server trusts the secure connection against the specified fixed certificate or public key. TL;DR adds your server certificate to the app bundle to help prevent man-in-the-middle attacks.
Accessibility

AFHTTPClientanother function from decoupling is the accessibility of the network. Now you can use it directly, or use AFHTTPRequestOperationManager AFHTTPSessionManager the/properties.

    • AFNetworkReachabilityManager-This class monitors the accessibility of the current network, providing callback blocks and Notificaiton, which are invoked when accessibility changes.
Real-time sex
    • AFEventSource- EventSource objective-c implementation of DOM API. Establish a persistent HTTP connection to a host that can transmit events to the event source and distribute them to the listener. The message that is transmitted to the event source is formatted as a JSON Patch file and is translated into AFJSONPatchOperation an array of objects. You can apply these patch operation to a persisted dataset that was previously obtained from the server. ~~~{OBJECTIVE-C} nsurl *url = [Nsurl urlwithstring:@ "http://example.com"]; Afhttpsessionmanager *manager = [[Afhttpsessionmanager alloc] initwithbaseurl:url]; [Manager get:@ "/resources" Parameters:nil success:nsurlsessiondatatask *task, id responseobject {[resources addobjectsfromarray:responseobject[@ "Resources"];

      [Manager subscribe:@ "/resources" Usingblock:nsarray *operations, Nserror *error {for (afjsonpatchoperation *operation In operations) {switch (operation.type) {case Afjsonaddoperationtype: [Resources AddObject:operation.value]; Ault:break; }}} Error:nil]; } Failure:nil]; ~~~

UIKit extension

All the UIKit category in the previous afnetworking have been retained and enhanced, and some new category additions have been added.

    • AFNetworkActivityIndicatorManager: Automatically starts and stops the network activity indication icon on the status bar when the request operation starts and stops loading.
    • UIImageView+AFNetworking: Added imageResponseSerializer properties to make it easy to automatically resize or apply a filter to an image that is loaded remotely onto an image view. For example, AFCoreImageSerializer you can apply the Core image filter before the response image is displayed.
    • UIButton+AFNetworking(New): With UIImageView+AFNetworking similar, loaded from remote resources image and backgroundImage .
    • UIActivityIndicatorView+AFNetworking(New): Automatically starts and stops based on the specified request action and the State of the session task UIActivityIndicatorView .
    • UIProgressView+AFNetworking(New): Automatically tracks the upload/download progress of a request or session task.
    • UIWebView+AFNetworking(New): Provides a more powerful API for loading URL requests, supporting progress callbacks and content conversions.

So finally to end the afnetworking whirlwind journey. New features designed for next-generation applications, combined with a new architecture for existing features, are a lot of things to be excited about.

Hit

Add the following code Podfile to start playing afnetworking 2.0:

platform :ios, ‘7.0‘pod "AFNetworking", "2.0.0"

For anyone coming-afnetworking from the current 1.x release, your may find the Afnetworking 2.0 Migration Guide ESP Ecially useful.

For users who are transferred from the Afnetworking 1.x version to the new version, you can find the Afnetworking 2.0 Migration Guide.

If you encounter bugs or other strange places, please help us improve by opening a question on GitHub. Thank you very much for your help.

For general usage issues, please feel free to tweet me @AFNetworking, or email me.

IOS 8: "Go" afnetworking 2.0

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.