本篇文章中,笔者将着重挑选了AFNetworking官方文档中的使用部分进行了翻译。关于Pod以及Carthage安装第三方库的部分,可以参考笔者相关文章。官方源码地址传送门为https://github.com/AFNetworking/AFNetworking。
1. 框架体系
1.1 NSURLSession
- AFURLSessionManager
- AFHTTPSessionManager
1.2 序列化
-
<AFURLRequestSerialization>
- AFHTTPRequestSerializer
- AFJSONRequestSerializer
- AFPropertyListRequestSerializer
-
<AFURLResponseSerialization>
- AFHTTPResponseSerializer
- AFJSONResponseSerializer
- AFXMLParserResponseSerializer
- AFXMLDocumentResponseSerializer (Mac OS X)
- AFPropertyListResponseSerializer
- AFImageResponseSerializer
- AFCompoundResponseSerializer
1.3 附加功能
- AFSecurityPolicy
- AFNetworkReachabilityManager
2. 使用方法
2.1 AFURLSessionManager
AFURLSessionManager用于,基于一个指定的NSURLSessionConfiguration对象,创建和管理NSURLSession对象。
它服从<NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>,<NSURLSessionDownloadDelegate>,和<NSURLSessionDelegate>等协议。
2.1.1 创建一个下载任务
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];
2.1.2 创建一个上传任务
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];
2.1.3 创建一个具有进度的多部件上传任务
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]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
其中,多部件请求为一次上传多个文件,例如;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[@"11230953" dataUsingEncoding:NSUTF8StringEncoding] name:@"uid"];
[formData appendPartWithFileData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myText" ofType:@"txt"]] name:@"file" fileName:@"myText.txt" mimeType:@"text/plain"];
} error:nil];
2.1.4 创建一个数据
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
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];
2.2 请求序列化
请求序列化从URL字符串创建请求,并将参数编码为查询字符串或HTTP主体。
NSString * URLString = @“ http://example.com ” ;
NSDictionary * parameters = @ { @“ foo ”:@“ bar ”,@“ baz ”:@ [@ 1,@ 2,@ 3 ]};
2.2.1 查询字符串参数编码
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
2.2.2 URL格式参数编码
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
2.2.3 JSON参数编码
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
2.3 网络连接管理
AFNetworkReachabilityManager用于监视域名的可达性,以及WWAN和WiFi网络接口的地址。
- 不要用可达性来决定,是否应该发送原始请求。
- 你应该尝试发送它。
- 您可以使用可达性来决定,何时应自动重试请求。
- 可达性通知(连接可用)是发起重试时间的好时机,虽然它可能仍然失败。
- 网络可达性,是确定请求可能失败原因的一个有用工具。
- 在网络请求失败之后,告诉他们离线的用户比给予他们一个更为技术性但准确的错误,比如“请求超时”。
2.3.1 共享网络可达性
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
2.4 安全策略
AFSecurityPolicy用来在安全的连接上,针对固定的X.509证书和公钥,评价服务器的可靠性。
将固定SSL证书添加到您的应用程序,有助于防止中间人攻击和其他漏洞。强烈建议,涉及到敏感客户数据或财务信息的应用程序应通过HTTPS路由到所有通信,配置并启用SSL pinning。
2.4.1 允许无效的SSL证书
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager ];
manager.securityPolicy.allowInvalidCertificates = YES ; //不推荐用于生产
3. 单元测试
AFNetworking在Tests子目录中包含了一套单元测试。这些测试可以简单地运行,以执行在您想要测试的平台框架上的测试操作。
翻译说明:
本文翻译自AFNetworking,版权归官方所有,翻译仅供学习用途,以上。