[翻译] Working with 发展历史NSULacrosseLSession: AFNetworking 2.0

Working with NSURLSession: AFNetworking 2.0

 

一言以蔽之翻译,有许多荒谬,看官不只怕知晓处请英文原文对照.

http://code.tutsplus.com/tutorials/working-with-nsurlsession-afnetworking-20–mobile-22651

by Bart
Jacobs
3 Feb 2014

In the previous installments of this series, we’ve taken a close look at
the NSURLSession API introduced in iOS 7 and OS X Mavericks.
Networking on iOS and OS X has become much simpler and more flexible
thanks to the NSURLSession API. Does this mean that you should stop
using AFNetworking for your networking needs? And what about
AFNetworking 2.0, which was introduced a few months ago? In this final
installment, I will tell you about AFNetworking 2.0 and how it compares
to the NSURLSession API.

在事先的一多级教程当中,我们早就仔细的解析了
NSU大切诺基LSession 的 API,他是 iOS 7 以及 OS X
新引入的处理网络链接的章程。近期,处理互连网越来越简单,小白都能自由上手了,那得益于
NSUOdysseyLSession
的提携啊,亲。纵然小白都能整精晓互连网是怎么回事,是还是不是代表不须求拔取开源库
AFNetworking 了吧? AFNetworking 2.0
到底具备什么样的风味呢?在那最终的一期教程当中,哥来引领你们,举行AFNetworking 2.0 与 NSURubiconLSession 之间的深浅相比。

Introduction (介绍)

By all accounts, AFNetworking is about as mainstream as it gets.

As Mattt Thompson points out on
NSHipster,
AFNetworking has become
the de facto networking library for Cocoa applications. At the time of
writing, the library has surpassed 10,000 stars on
GitHub
and was forked
close to 3,000 times.

If you’re new to AFNetworking and would like to read more about its
history and features, then I suggest to read Mattt’s post about
AFNetworking 2.0 on NSHipster.
In this article, I’d like to focus on two aspects, what is new in
AFNetworking 2.0 and how does it compare to the NSURLSession API . The
question you should be asking yourself is “Should I still be using
AFNetworking with NSURLSession in my toolbox?” That’s the question I
plan to answer in this article.

不管怎么样,AFNetworking
都以3个风传。

正如 Mattt Thompson 在 NSHipster 上提出的,AFNetworking 实际上已经成为了
Cocoa
应用中必备的3个开源库。当下还在不停的护卫着,这一个开源库已经赢得了当先10,000人的支撑,被fork了接近3,000数十次。

一旦,你还没听过 AFNetworking
(哥真的鄙夷你-_-!!),想打听一下她前进的野史以及一些牛逼的风味,那样的话,哥提出你读一下 马特t
的博文 AFNetworking 2.0 on
NSHipster
 。
 在今天你看的那篇博文中,作者将根本聚焦在多少个方面,AFNetworking 2.0
有何新的特征,它与 NSUPAJEROLSession API
之间到底有甚分裂。你应该问一下您本人:“作者是或不是还要用 AFNetworking 配合NSRULSession 来拍卖网络呢?”那就是哥要回到你的题材。

Requirements(一些标准)

Before we take a closer look at what AFNetworking 2.0 has to offer, it’s
important to know about the library’s new requirements. It shouldn’t be
a surprise that the requirements of AFNetworking 2.0 are stricter than
those of AFNetworking 1.x. As its version number indicates, AFNetworking
includes breaking changes, which are the result of its new architecture.
This also means that migrating a project from AFNetworking 1.x to 2.0
should be done with caution. The migration
guide

is the ideal place to start if you plan on migrating a project to
AFNetworking 2.0.

AFNetworking no longer supports iOS 4.3 and 5. The minimum deployment
targets for iOS and OS X are iOS 6 and OS X 10.8 respectively.
AFNetworking 2.0 also requires Xcode 5. If you’re still using Xcode 4,
this may be a good time to make the transition to Xcode 5.

在我们越发询问 AFNetworking 2.0
此前,知道那些开源库有着什么样的新的环境须要格外主要。正如他的本子号标示的这样子,AFNetworking
2.0 比 AFNetworking 1.x
有着更严酷的限量标准,它拥有许多簇新的架构级的变更,和原先曾经愈演愈烈了。也等于说,你不要手贱把以前的
AFNetworking 1.x 的类型升级到 AFNetworking
2.0,否则会冒出众多的警告,就算您确实想升官一下,恩,migration
guide
 这些指南应该是你的菜。

Solid Foundation(基础介绍)

AFURLConnectionOperation

As many of you probably know, AFNetworking is built on top of
NSURLConnection and NSOperation, which has proven to be a powerful
and elegant combination. The result of this combination is
AFURLConnectionOperation, an NSOperation subclass that manages an
NSURLConnection instance and implements the NSURLConnectionDelegate
protocol. Even though this robust foundation remains unchanged in
AFNetworking 2.0, it is supplemented by the NSURLSession API, which
I’ll cover in more detail later.

兴许你早已精晓了, AFNetworking 是在
NSURLConnection 以及 NSOperation 的根基上包裹的,以后已经表达,
NSURLConnection
NSOperation 的组合使用非常的优雅.这个组合的结果就是 AFURLConnectionOperation
,一个 NSOperation 的子类来治本二个
NSURLConnection 的实例,并且实现协议 NSURLConnectionDelegate.这种健康的结缘,固然是升格到了
AFNetworking 2.0 也并未变动,而 NSURLSession API
那货就是补偿的,直至今才知道这么玩,前边小编会详细的解说.

Separation of Responsibilities

In AFNetworking 1.x, the AFHTTPRequestOperation发展历史, class was in charge of
request and response serialization and validation. This is no longer
true in AFNetworking 2.0. The AFHTTPRequestOperation class and its
subclasses are no longer directly responsible for serializing and
validating requests and responses. This responsibility has been moved to
the AFURLRequestSerialization and AFURLResponseSerialization
protocols. Each protocol declares a single delegate method to handle
request and response serialization and validation respectively.

在 AFNetworking 1.x 中,
AFHTTPRequestOperation 是用来管理网络请求 request 以及网络回复 response 的.在 AFNetworking 2.0 中,已经不再是这样子的了. AFHTTPRequestOperation 以及它的子类不会直接管理他们.操作以及回复被移到了 AFURLRequestSerialization
以及 AFURLResponseSerialization
协议中.每三个协商定义了2个办法,用来管理请求以及回复.

To make your life easier, however, AFNetworking 2.0 ships with
AFHTTPRequestSerializer and AFHTTPResponseSerializer as well as a
number of subclasses for common content types, such as JSON and XML. To
see how this works in practice, let’s take a look at an example in which
I query the Forecast API. This doesn’t look all that different from how
you made a request with AFNetworking 1.x. The main difference is that
you’ll be using the AFHTTPRequestOperation class more often. The
AFJSONRequestOperation and AFXMLRequestOperation classes are no
longer present in AFNetworking 2.0.

为了让你写代码写得更爽,AFNetworking 2.0 将
AFHTTPRequestSerializer AFHTTPResponseSerializer
以及通用的一些数据类型如 JSON 和 XML
等捆绑在一起.让大家来看七个例证,那一个例子中本人来调用二个天气预告的接口.在与行使
AFNetworking 1.x 比较时,不会有太大的界别,主要的两样就是你会平时的运用
AFHTTPRequestOperation,在 AFNetworking 2.0 中,AFJSONRequestOperation
AFXMLRequestOperation 已经被移除了.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
NSString *key = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.forecast.io/forecast/%@/37.8267,-122.423", key]];
 
// Initialize Request Operation
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:URL]];
 
// Configure Request Operation
[requestOperation setResponseSerializer:[AFJSONResponseSerializer serializer]];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Process Response Object
 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Handle Error
}];
 
// Start Request Operation
[requestOperation start];

The AFJSONResponseSerializer class inherits from
AFHTTPResponseSerializer and should be used for JSON responses. If you
need to process XML responses, then AFXMLNResponseSerializer will help
you out. For other content types, you need to subclass
AFHTTPResponseSerializer.

AFJSONResponseSerializer 那些类继承至
AFHTTPResponseSerializer ,他是用来分析
JSON的,假使你须要解析XML数据,那这几个 AFXMLNResponseSerializer
就是您的菜.对于有个别其余的数据类型,你需求继续他们的子类就行了.

AFHTTPRequestOperationManager

Another major change in AFNetworking 2.0 is the removal of the
AFHTTPClient class, which was in charge of talking to web services.
The responsibilities of AFHTTPClient have been split up into a number
of classes and protocols. To talk to a web service, you now use
AFHTTPRequestOperationManager and AFHTTPSessionManager. Just like
AFHTTPRequestOperation, AFHTTPRequestOperationManager and
AFHTTPSessionManager delegate serialization of requests and responses
to separate objects. Both AFHTTPRequestOperationManager and
AFHTTPSessionManager have a requestSerializer and
responseSerializer property for this purpose. Let’s revisit the above
example to see how this works in practice.

AFNetworking 2.0 其它2个变动就是移除了
AFHTTPClient , AFHTTPClient 是用来与web服务器交互的, AFHTTPClient
的效用已经被分割成一各个的类和商谈了.为了与 web
服务器交互,近年来,你必要利用
AFHTTPRequestOperationManager 和 AFHTTPSessionManager.就像 AFHTTPRequestOperation
AFHTTPRequestOperationManager AFHTTPSessionManager 以及一系列的协议那样来处理不同的请求与对象.AFHTTPRequestOperationManager
AFHTTPSessionManager 都有 requestSerializer 以及
responseSerializer 这一个天性,让我们再来看看上边的例子.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
NSString *key = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.forecast.io/forecast/%@/", key]];
 
// Initialize Request Operation Manager
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
 
// Configure Request Operation Manager
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
 
// Send Request
[manager GET:@"37.8267,-122.423" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Process Response Object
 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Handle Error
}];

What About NSURLSession?(什么是NSURLSession

AFURLSessionManager

The key question when discussing AFNetworking 2.0 in the light of the
NSURLSession API is whether we still need AFNetworking. AFNetworking
adds a number of convenience classes and methods to the NSURLSession
API and this is only possible thanks to the separation of
responsibilities I discussed earlier. The most significant improvement
that AFNetworking provides on top of the NSURLSession API are the
AFURLSessionManager and AFHTTPSessionManager classes.

主干难点中,大家谈谈了是或不是还需求运用
AFNetworking 2.0 ,AFNetworking 添加了成千成万方便的点子到 NSURLSession
API
中,在上文中大家谈谈过了,这些网络种种过来的分手是很有裨益的.最为大旨的句斟字酌就是,AFNetworking
NSURLSession API 之上提供了AFURLSessionManager
AFHTTPSessionManager 那七个类.

The AFURLSessionManager helps you manage an NSURLSession object.
Even though I love the NSURLSession API, I have to agree with Mattt
that its API is incomplete. The AFURLSessionManager class adds a
number of convenience methods that make the NSURLSession API even
better. Serialization and validation, for example, are much easier and
intuitive with AFNetworking. Just like the
AFHTTPRequestOperationManager, instances of AFURLSessionManager have
a requestSerializer and responseSerializer property that makes
serialization of requests and responses seamless and intuitive.

AFURLSessionManager 辅助您管理
NSURLSession对象.纵然哥很喜欢 NSURLSession 的 API ,但是,正如
马特t说说,那么些 API 是不健全的.AFURLSessionManager
添加了一层层的便利的格局来扩张了 NSURLSession 的 API. 就像是使用
AFHTTPRequestOperationManager 那样,实例化三个 AFURLSessionManager
对象将有 requestSerializer
responseSerializer 属性,他们可以让序列化的网络请求以及网络回复无缝衔接,非常方便.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
NSString *key = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.forecast.io/forecast/%@/37.8267,-122.423", key]];
 
// Initialize Session Configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
 
// Initialize Session Manager
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];
 
// Configure Manager
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
 
// Send Request
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    // Process Response Object
}] resume];

I hope you can see the benefit of using AFNetworking in combination with
the NSURLSession API. It makes working with the NSURLSession API
much more intuitive especially if you’re already used to the way
AFNetworking 2.0 separates serialization and validation from the actual
task or request operation.

本身盼望您能清楚 AFNetworking 合并了
NSURLSession API的好处.它让使用 NSURLSession API
尤其的直观,更加是,你已近习惯了 AFNetworking 2.0
分割种类化以及确认的操作,便利于当前的互连网操作.

AFHTTPSessionManager

AFNetworking 2.0 also incudes a subclass of AFURLSessionManager,
AFHTTPSessionManager, which makes interacting with web services a
breeze. The AFHTTPSessionManager class includes a number of
conveniences methods, such as GET:parameters:success:failure: and
POST:parameters:constructingBodyWithBlock:success:failure: that make
the migration process from AFHTTPClient to AFHTTPSessionManager
easy. Similar methods are also available in the
AFHTTPRequestOperationManager class, which I discussed earlier.

AFNetworking 2.0 也有子类叫
AFURLSessionManager , AFHTTPSessionManager
,它让与服务器交互变得小菜一碟. AFHTTPSessionManager
那些类富含了有些有利于的法子,例如, GET:parameters:success:failure: 以及
POST:parameters:constructingBodyWithBlock:success:failure: ,它衔接了从 AFHTTPClient
AFHTTPSessionManager 的操作,使其更易于采纳,同样的,
AFHTTPRequestOperationManager 也有那个,后边商量.

Reachability(网络是否畅通

Reachability is managed by the AFURLRequestOperationManager and
AFURLSessionManager classes. When instances of these classes have a
valid baseURL, then a reachability manager is automatically
instantiated and set up. Of course, it is also possible to explicitly
create an instance of the AFNetworkReachabilityManager class.

AFURLRequestOperationManager
AFURLSessionManager 这些类已经管理了网络是否畅通了,当实例化这些对象后,传了一个合法的 URL 地址,那么,监测网络就会自动执行.当然,你也可以直接就显示的实例化 AFNetworkReachabilityManager
来达到目标.

Icing On The Cake(锦上添花

AFNetworking 2.0 has a number of other features, such as built-in
support for SSL pinning and various categories on UIKit classes. Take a
look at this example in which I leverage AFNetworking’s category on
UIProgressView to update a progress view while downloading a remote
image.

AFNetworking 2.0
有着众多其余的本性,例如内置扶助 SSL pinning 以及一体系的类目扩充UIKit,来看一下下边那么些事例把,小编用AFNetworking的类目来促使
UIProgressView 更新下载进程,当正在下载一张图纸时.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
// Initialize Request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.tutsplus.com/mobile/uploads/2014/01/5a3f1-sample.jpg"]];
 
// Initialize Session Manager
self.sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
 
// Initialize Download Task
NSURLSessionDownloadTask *downloadTask = [self.sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    // Handle Success
 
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    // Handle Failure
}];
 
[self.progressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
 
[downloadTask resume];

 

Verdict(裁决

If your project doesn’t rely on networking, then you won’t need all the
power and convenience that AFNetworking has to offer. As a matter of
fact, I think it’s important that every iOS or OS X developer is
familiar with NSURLSession and NSURLConnection, because they are key
components of the platform.

倘若你的项目中不器重于网络,那么您恐怕就不要求AFNetworking 给你提供的那一个强大的成效.可是,实际上,作者认为,对于每贰个iOS
和 OSX的开发者而言,熟识 NSURLSession 以及 NSURLConnection
非凡有需求,因为她们是以此开发平台的2个基本模块.

Even though the NSURLSession API is great and easy to use, the
networking APIs provided by the Foundation framework aren’t perfect. As
Mattt points out, even the NSURLSession API has a few notable gaps.
AFNetworking tries to elegantly fill these gaps. The combination of the
NSURLSession API and AFNetworking is a marriage made in heaven. It
truly is a joy to use.

虽然 NSURLSession 的 API
很牛逼而且很好用,不过,Foundation framework 提供的网络有关的 API
依然不到家, 马特t 指出,NSURLSession API 有着一些弱点, 正是
AFNetworking 来弥补了那几个,将 NSURLSession API 以及 AFNetworking
组合在一齐真是天上一对地上一双.用起来会让你卓殊的爽.

I really like the NSURLSession API and I hope I’ve convinced you of
its power in this series. However, this doesn’t mean that AFNetworking
has become obsolete. In my opinion, AFNetworking is the perfect
companion of the NSURLSession API. AFNetworking has matured and it is
indeed the best and most robust networking library available. Its
modular architecture means that you don’t need to include every class or
category it has to offer. You are free to pick and choose from the
components that it includes. AFNetworking supports CocoaPods
subspecs
,
which make this process trivial.

本人真正喜欢 NSURLSession API
,我也坚信自个儿曾经传话了它牛逼的地点.那一个不是说 AFNetworking
就变得不那么重大了.笔者的见识是,AFNetworking 是 NSURLSession API
最好的搭档.AFNetworking
以及成熟了,而且,他也着实是日前最成熟的互连网框架.它那模块化的架构意味着,你不需求包罗它全部的文件到您的工程当中.你可以肆意的选用你想用的组件到您的工程当中.

Conclusion(结论

I couldn’t be more happy with the second major release of AFNetworking.
The library’s modularity and separation of responsibilities is what
makes it shine in my opinion. It complements the NSURLSession API so
well that you won’t even notice that you’re using AFNetworking. Mattt
Thompson and the more than 130 contributors of AFNetworking have done a
formidable job. It’s good to be a Cocoa developer.

对于第①个本子的 AFNetworking
的自由,哥真的相当的安心乐意.那几个库的模块化以及不一致部分分担不一致的职分让它不行的出众.它填补了
NSURLSession API ,让你意识不到你正在使用 AFNetworking, 马特t Thompson以及 1二1陆个进献代码的人做了二个令人敬佩的工作.作为苹果的开发人士,哥真的很幸福.

 

 

 

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注