[翻译] Working with ca88手机版登录网页NSURLSession: 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.

在后边的一层层教程当中,咱们早已仔细的解析了
NSURLSession 的 API,他是 iOS 7 以及 OS X
新引入的拍卖互联网链接的形式。方今,处理互联网越发不难,小白都能随便上手了,那得益于
NSURLSession
的增援啊,亲。固然小白都能整精晓互联网是怎么回事,是或不是意味着不必要使用开源库
AFNetworking 了啊? AFNetworking 2.0
到底持有怎么着的特征呢?在那最终的一期教程当中,哥来引领你们,进行AFNetworking 2.0 与 NSURLSession 之间的纵深相比较。

ca88手机版登录网页 1

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
都以一个传说。

正如 Mattt Thompson 在 NSHipster 上提议的,AFNetworking 实际上已经改成了
Cocoa
应用中必备的一个开源库。当下还在不停的爱慕着,这几个开源库已经取得了跨越10,000人的支撑,被fork了接近3,000多次。

如若,你还没听过 AFNetworking
(哥真的鄙视你-_-!!),想打听一下她前进的历史以及一些牛逼的性状,那样的话,哥提出您读一下 Mattt
的博文 AFNetworking 2.0 on
NSHipster
 。
 在前几天您看的那篇博文中,我将重视聚焦在七个地方,AFNetworking 2.0
有哪些新的特征,它与 NSURLSession API
之间终归有甚差别。你应该问一下您本身:“我是还是不是还要用 AFNetworking 合营NSRULSession 来处理互联网呢?”那就是哥要回到你的题材。

老牌的开源互联网库AFNetworking
2.0,近日只是翻译了Github上的链接作品,使用教程请点击

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
 那些指南应该是您的菜。

http://www.cnblogs.com/YouXianMing/p/3651462.html

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
这货就是互补的,直于今才知道这么玩,前边我会详细的解说.

https://github.com/AFNetworking/AFNetworking

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
协议中.每种研商定义了一个格局,用来治本请求以及回复.

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 此外一个变动就是移除了
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
}];

AFNetworking is a delightful networking library for iOS and Mac OS X.
It’s built on top of the Foundation URL Loading
System
,
extending the powerful high-level networking abstractions built into
Cocoa. It has a modular architecture with well-designed, feature-rich
APIs that are a joy to use.

What About NSURLSession?(什么是NSURLSession

Perhaps the most important feature of all, however, is the amazing
community of developers who use and contribute to AFNetworking every
day. AFNetworking powers some of the most popular and
critically-acclaimed apps on the iPhone, iPad, and Mac.

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 ,不过,正如
Mattt说说,那么些 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
分割种类化以及确认的操作,便利于当前的网络操作.

Choose AFNetworking for your next project, or migrate over your existing
projects—you’ll be happy you did!

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 也有这个,前面琢磨.

行使AFNetworking那几个互连网库来开展开发会令你神清气爽。它创建在Foundation
URL Loading
System
的上层,给Cocoa强大的互联网库举行了高层次的伸张。它具备模块化的优质设计,囊括各个易用的API,亲,不用你就落后了。

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];

 

下一个工程中,采取AFNetworking吧,或然,在你眼下的品类少将它移植进来,我敢保险你会受益无穷的。

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
很是有必不可少,因为她们是这么些开发平台的一个着力模块.

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
仍旧不圆满, Mattt 指出,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
以及成熟了,而且,他也确确实实是现阶段最成熟的网络框架.它那模块化的架构意味着,你不要求包括它全体的公文到您的工程当中.你可以肆意的精选你想用的零件到您的工程当中.

How To Get Started(怎样开端)

  • Download
    AFNetworking
     and
    try out the included Mac and iPhone example apps
  • Read the “Getting Started”
    guide
    FAQ,
    or other articles on the
    Wiki
  • Check out
    the documentation for
    a comprehensive look at all of the APIs available in AFNetworking
  • Questions? Stack
    Overflow
     is
    the best place to find answers
  • 下载AFNetworking的源码,试一下Mac以及摩托罗拉下边的例证
  • 读入门指南,提问及回复,或许Wiki上的相干小说
  • 细心的探访AFNetworking提供的文档
  • 有难点了?上Stack Overflow吧

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, Mattt Thompson以及 130
个进献代码的人做了一个令人佩服的工作.作为苹果的开发人士,哥真的很幸福.

 

 

 

 

 

2.0

AFNetworking 2.0 is a major update to the framework. Building on 2 years
of development, this new version introduces powerful new features, while
providing an easy upgrade path for existing users.

AFNetworking
2.0有着很大的立异,建立在两年的开发并爱慕这些库的底子上,新本子带来了更多的表征,当然,他也不会放弃AFNetworking
1.x的用户,它提供了一个简便的如何从1.x升格到2.0的一篇文档。

Read the AFNetworking 2.0 Migration
Guide
 for
an overview of the architectural and API changes.

What’s New

  • Refactored Architecture
  • Support for NSURLSession
  • Serialization Modules
  • Expanded UIKit Extensions
  • Real-time functionality with Rocket
  • 重构了架构
  • 支持NSURLSession
  • 模块化的模型
  • 扩展了UIKit
  • ??????

Requirements(要求)

AFNetworking 2.0 and higher requires Xcode 5, targeting either iOS 6.0
and above, or Mac OS 10.8 Mountain Lion (64-bit with modern Cocoa
runtime
)
and above.

AFNetworking 2.0以及持续高版本需求在Xcode
5上展开销付,iOS版本要求6.0以及上述,Mac OS 10.8以及上述。

For compatibility with iOS 5 or Mac OS X 10.7, use the latest 1.x
release
.

For compatibility with iOS 4.3 or Mac OS X 10.6, use the latest 0.10.x
release
.

为了包容iOS 5可能Mac OS X
10.7,使用1.x版本。

为了包容iOS 4.3仍旧Mac OS X
10.6,使用0.10.x本子。

Architecture(结构)

NSURLConnection

  • AFURLConnectionOperation
  • AFHTTPRequestOperation
  • AFHTTPRequestOperationManager

NSURLSession (iOS 7 / Mac OS X 10.9)

  • AFURLSessionManager
  • AFHTTPSessionManager

ca88手机版登录网页,Serialization

  • <AFURLRequestSerialization>
    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer
  • <AFURLResponseSerialization>
    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer (Mac OS X)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

Additional Functionality

  • AFSecurityPolicy
  • AFNetworkReachabilityManager

Usage(使用)

HTTP Request Operation Manager(HTTP请求操作管理器)

AFHTTPRequestOperationManager encapsulates the common patterns of
communicating with a web application over HTTP, including request
creation, response serialization, network reachability monitoring, and
security, as well as request operation management.

AFHTTPRequestOperationManager 将通用的与服务器应用交互的操作封装了起来,包蕴了请求的创造,回复的种类化,互联网指示器的监测,安全性,当然还有请求操作的田间管理。

GET Request(GET请求)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

POST URL-Form-Encoded Request(附带表单编码的POST请求)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

POST Multi-Part Request(复杂的POST请求)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

AFURLSessionManager

AFURLSessionManager creates and manages an NSURLSession object based
on a specified NSURLSessionConfiguration object, which conforms
to <NSURLSessionTaskDelegate><NSURLSessionDataDelegate><NSURLSessionDownloadDelegate>,
and <NSURLSessionDelegate>.

AFURLSessionManager 创设了一个管制一个NSURLSession的靶子,基于一个点名的NSURLSessionConfiguration对象,它与以下的那一个协议融合在联名(<NSURLSessionTaskDelegate><NSURLSessionDataDelegate><NSURLSessionDownloadDelegate>,<NSURLSessionDelegate>)。

Creating a Download Task(制造一个下载职分)

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

Creating an Upload Task(成立一个上传职责)

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

Creating an Upload Task for a Multi-Part Request, with Progress(创建一个繁杂的央求,并顺便进程)

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"%@ %@", response, responseObject);
        }
    }];

    [uploadTask resume];

Creating a Data Task(创造一个数码任务)

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

Request Serialization(请求体系化)

Request serializers create requests from URL strings, encoding
parameters as either a query string or HTTP body.

呼吁系列化器会从URL字符串创设请求,编码参数,查找字符串只怕是HTTPbody部分。

NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};

Query String Parameter Encoding(查询string的编码)

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];

GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3

URL Form Parameter Encoding(查询URL表单情势参数的编码)

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

POST http://example.com/
Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3

JSON Parameter Encoding(查询json参数的编码)

[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

POST http://example.com/
Content-Type: application/json

{"foo": "bar", "baz": [1,2,3]}

Network Reachability Manager(监测网络管理器)

AFNetworkReachabilityManager monitors the reachability of domains, and
addresses for both WWAN and WiFi network interfaces.

AFNetworkReachabilityManager 监测域名以及IP地址的畅通性,对于WWAN以及WiFi的互连网接口都有效。

Shared Network Reachability(单例方式检测网络畅通性)

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

HTTP Manager with Base URL(用为重的URL管理HTTP)

When a baseURL is provided, network reachability is scoped to the host
of that base URL.

若果提供了一个为主的URL地址,那一个基本URL网址的畅通性就会被细心的监测着。

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue setSuspended:YES];
            break;
    }
}];

Security Policy

AFSecurityPolicy evaluates server trust against pinned X.509
certificates and public keys over secure connections.

Adding pinned SSL certificates to your app helps prevent
man-in-the-middle attacks and other vulnerabilities. Applications
dealing with sensitive customer data or financial information are
strongly encouraged to route all communication over an HTTPS connection
with SSL pinning configured and enabled.

Allowing Invalid SSL Certificates(允许不合规的SSL证书)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production

AFHTTPRequestOperation

AFHTTPRequestOperation is a subclass of AFURLConnectionOperation for
requests using the HTTP or HTTPS protocols. It encapsulates the concept
of acceptable status codes and content types, which determine the
success or failure of a request.

Although AFHTTPRequestOperationManager is usually the best way to go
about making requests, AFHTTPRequestOperation can be used by itself.

AFHTTPRequestOperation继承自AFURLConnectionOperation,使用HTTP以及HTTPS协议来处理网络请求。它封装成了一个可以令人接受的代码形式。当然AFHTTPRequestOperationManager 方今是最好的用来拍卖互联网请求的点子,但AFHTTPRequestOperation 也有它和谐的用武之地。

GET with AFHTTPRequestOperation(使用AFHTTPRequestOperation)

NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];

Batch of Operations(许多操作一起开展)

NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [mutableOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图