简介
iOS APP发起网络请求,都离不开一个非常有用的第三方框架[AFNetworking](https://github.com/AFNetworking/AFNetworking),可以说这个框架的知名度已经超过了苹果的底层网络请求部分,很多人可能不知道苹果底层是如何发起网络请求的,但是一定知道AFNetworking,接下来我们就详细的了解一下这个框架。
1.我们来看一下AFNetworking的基本结构


2.0 由图片可以看出 AFNetworking 主要分为以下几个部分
NSURLSession
- AFURLSessionManager (处理NSURLSession的代理的管理类)
- AFHTTPSeesionManager (AFURLSessionManager 的子类)
Serialization
- 遵守 <AFURLRequestSerialization> 协议的请求处理辅助类
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer - 遵守 <AFURLResponseSerialization> 协议的返回处理辅助类
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer (macOS)
AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
Additional Functionality
- AFSecurityPolicy(安全策略类)
- AFNetworkReachabilityManager(网络状态辅助类)
UIKit分类以及相关的下载缓存
类+ UIActivityIndicatorView+AFNetworking
- UIButton+AFNetworking
- UIImage+AFNetworking
- UIImageView+AFNetworking
- UIProgressView+AFNetworking
- UIRefreshControl+AFNetworking
- UIWebView+AFNetworking
- AFAutoPurgingImageCache
- AFImageDownloader
3.0 简单使用
- AFURLSessionManager
AFURLSessionManager基于遵循<NSURLSessionTaskDelegate>,<NSURLSessionDataDelegate>,<NSURLSessionDownloadDelegate>和<NSURLSessionDelegate>的指定NSURLSessionConfiguration对象创建和管理NSURLSession对象。
创建 data task 普通的数据任务
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];
创建一个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];
创建一个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];
2.1 AFURLRequestSerialization
在iOS原生的request 中每个地方的request的url字符串需要手动拼接,耗时耗力,而在AF中拼接请求的参数和正文被封装到了请求序列化器中,可以方便的把参数编码为查询字符串或HTTP正文。
- (void)demo4
{
NSString *URLString = @"http://www.ppf.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
//1.0 Request GET 查询字符串参数编码 Query String Parameter Encoding
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSURLRequest *rq1 = [serializer requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
/*
GET http://www.ppf.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
*/
//2.0 Request POST URL表单参数编码 URL Form Parameter Encoding
NSURLRequest *rq2 = [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
*/
//3.0 Request PUT
NSURLRequest *rq3 = [serializer requestWithMethod:@"PUT" URLString:URLString parameters:parameters error:nil];
NSLog(@"PUT %@",rq3);
/*
PUT <NSMutableURLRequest: 0x60400001f300> { URL: http://www.ppf.com, Method PUT, Headers {
"Accept-Language" = (
"en;q=1"
);
"Content-Type" = (
"application/x-www-form-urlencoded"
);
"User-Agent" = (
"PPFTest/1.0 (iPhone; iOS 11.1; Scale/3.00)"
);
} }
*/
//4.0 JsonRequest GET
NSURLRequest *jsonRq1 = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
NSLog(@"json GET %@",jsonRq1);
//打印
/*
json GET <NSMutableURLRequest: 0x600000014f80> { URL: http://www.ppf.com?baz%5B%5D=1&baz%5B%5D=2&baz%5B%5D=3&foo=bar, Method GET, Headers {
"Accept-Language" = (
"en;q=1"
);
"User-Agent" = (
"PPFTest/1.0 (iPhone; iOS 11.1; Scale/3.00)"
);
} }
*/
//5.0 JsonRequest POST -JSON参数编码 JSON Parameter Encoding
NSURLRequest *jsonRq2 = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
/*
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
*/
//6.0 JsonRequest PUT
NSURLRequest *jsonRq3 = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:URLString parameters:parameters error:nil];
NSLog(@"json PUT %@",jsonRq3);
/*
json PUT <NSMutableURLRequest: 0x600000014e20> { URL: http://www.ppf.com, Method PUT, Headers {
"Accept-Language" = (
"en;q=1"
);
"Content-Type" = (
"application/json"
);
"User-Agent" = (
"PPFTest/1.0 (iPhone; iOS 11.1; Scale/3.00)"
);
} }
*/
}
3. Network Reachability Manager
AFNetworkReachabilityManager监控网络状态,以及WWAN和WiFi网络接口的地址。
4. Security Policy
AFSecurityPolicy通过安全连接评估针对固定的X.509证书和公钥的服务器信任。
将固定的SSL证书添加到您的应用程序有助于防止中间人攻击和其他漏洞。 强烈建议处理敏感客户数据或财务信息的应用程序通过HTTPS连接路由所有通信,并配置启用SSL pinning。
网友评论