[翻译] AFNetworking 2.0
大名鼎鼎的开源网络库AFNetworking 2.0,目前只是翻译了Github上的链接文章,使用教程请点击
http://www.cnblogs.com/YouXianMing/p/3651462.html
https://github.com/AFNetworking/AFNetworking
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.
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.
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
使用AFNetworking这个网络库来进行开发会令你神清气爽。它建立在Foundation URL Loading System的上层,给Cocoa强大的网络库进行了高层次的扩展。它具有模块化的精良设计,囊括各种易用的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以及iPhone上面的例子
- 读入门指南,提问及答复,或者Wiki上的相关文章
- 细致的看看AFNetworking提供的文档
- 有问题了?上Stack Overflow吧
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
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];
[翻译] AFNetworking 2.0的更多相关文章
- [翻译] Working with NSURLSession: AFNetworking 2.0
Working with NSURLSession: AFNetworking 2.0 简单翻译,有很多错误,看官无法理解处请英文原文对照. http://code.tutsplus.com/tu ...
- AFNetworking 3.0 源码解读(八)之 AFImageDownloader
AFImageDownloader 这个类对写DownloadManager有很大的借鉴意义.在平时的开发中,当我们使用UIImageView加载一个网络上的图片时,其原理就是把图片下载下来,然后再赋 ...
- AFNetworking 3.0迁移指南
AFNetworking是一款在OS X和iOS下都令人喜爱的网络库.为了迎合iOS新版本的升级, AFNetworking在3.0版本中删除了基于 NSURLConnection API的所有支持. ...
- [置顶] AFNetworking 2.0 新特性讲解之AFHTTPSessionManager
AFNetworking 2.0 相比1.0 API 接口改动还是很大的. 其中一个便是 AFURLSessionManager,当然如果你不太熟悉,或者为了兼容低版本,你依然可以选择AFHTTPRe ...
- AFNetworking 2.0 新特性讲解之AFHTTPSessionManager
AFNetworking 2.0 新特性讲解之AFHTTPSessionManager (2014-02-17 11:56:24) 转载▼ AFNetworking 2.0 相比1.0 API ...
- [转]AFNetworking 3.0迁移指南
http://www.jianshu.com/p/047463a7ce9b?utm_campaign=hugo&utm_medium=reader_share&utm_content= ...
- AFNetworking 3.0 源码解读 总结(干货)(下)
承接上一篇AFNetworking 3.0 源码解读 总结(干货)(上) 21.网络服务类型NSURLRequestNetworkServiceType 示例代码: typedef NS_ENUM(N ...
- AFNetworking 3.0 源码解读(十一)之 UIButton/UIProgressView/UIWebView + AFNetworking
AFNetworking的源码解读马上就结束了,这一篇应该算是倒数第二篇,下一篇会是对AFNetworking中的技术点进行总结. 前言 上一篇我们总结了 UIActivityIndicatorVie ...
- AFNetworking 3.0 源码解读(十)之 UIActivityIndicatorView/UIRefreshControl/UIImageView + AFNetworking
我们应该看到过很多类似这样的例子:某个控件拥有加载网络图片的能力.但这究竟是怎么做到的呢?看完这篇文章就明白了. 前言 这篇我们会介绍 AFNetworking 中的3个UIKit中的分类.UIAct ...
随机推荐
- C#socket编程序(三)
private void ReceiveData() { bool keepalive = true; Socket s = clientSocket; Byte[] buffer = new Byt ...
- 将C++ IplImage 图像用C#读取
如何将C++ IplImage 图像用C#读取 ? 将opencv 的C++程序做成 dll 动态链接库 用C#调用 当然这里需要安装emgucv ,也可以自己实现这个类. 下面我把实现贴出来给大 ...
- java程序员修炼之道——大牛告诉我们应该好好学习与修炼以下知识与技能
—————————— ASP.Net+Android+IOS开发..Net培训.期待与您交流! —————————— 一:Java语言学习(对线程(thread),串行化,反射,网络编程,JNI技术, ...
- hdoj1203 I NEED A OFFER!(DP,01背包)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1203 思路 求最少能收到一份offer的最大概率,可以先求对立面:一份offer也收不到的最小概率,然 ...
- 谷歌pagerank算法简介
在这篇博客中我们讨论一下谷歌pagerank算法.这是参考的原博客连接:http://blog.jobbole.com/71431/ PageRank的Page可是认为是网页,表示网页排名,也可以认为 ...
- 深入理解Git - Git底层对象
前篇: 深入理解Git - 一切皆commit 如何从稍微底层一点的角度,从底层实现理解一切皆commit ? 配合希沃白板课件食用,效果更佳: [希沃白板5]课件分享 : <Git 进阶 - ...
- Leaving Auction CF 749D
题目:http://codeforces.com/problemset/problem/749/D 题目大意: 有n个人竞拍,也有n个叫牌,一个人可以有多个叫价牌,但也可能有一些人根本不叫价 每个叫牌 ...
- Jquery的方法(二)
一.文档操作1.html()和text()的区别 <div id="J_div"><b><i>我是谁</i></b>&l ...
- [ 原创 ]Centos 7.0下安装 Tomcat8.5.15
Tomcat下载地址:http://tomcat.apache.org/download-80.cgi#8.5.15 上传到文件夹 并解压缩 出现问题: 解决方法: http://blog.csdn. ...
- codevs 2577 医院设置
2577 医院设置 时间限制: 1 s 空间限制: 32000 KB 题目等级 : 黄金 Gold 题目描述 Description 设有一棵二叉树,如下图 其中,圈中数字表示结点居民的人口.圈边 ...