本篇文章中揪荣,筆者將著重挑選了AFNetworking官方文檔中的使用部分進(jìn)行了翻譯迁霎。關(guān)于Pod以及Carthage安裝第三方庫(kù)的部分,可以參考筆者相關(guān)文章抵屿。官方源碼地址傳送門為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用于丐重,基于一個(gè)指定的NSURLSessionConfiguration對(duì)象,創(chuàng)建和管理NSURLSession對(duì)象拱层。
它服從<NSURLSessionTaskDelegate>弥臼,<NSURLSessionDataDelegate>,<NSURLSessionDownloadDelegate>根灯,和<NSURLSessionDelegate>等協(xié)議径缅。
2.1.1 創(chuàng)建一個(gè)下載任務(wù)
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 創(chuàng)建一個(gè)上傳任務(wù)
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 創(chuàng)建一個(gè)具有進(jìn)度的多部件上傳任務(wù)
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];
其中掺栅,多部件請(qǐng)求為一次上傳多個(gè)文件,例如纳猪;
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 創(chuàng)建一個(gè)數(shù)據(jù)
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 請(qǐng)求序列化
請(qǐng)求序列化從URL字符串創(chuàng)建請(qǐng)求氧卧,并將參數(shù)編碼為查詢字符串或HTTP主體。
NSString * URLString = @“ http://example.com ” ;
NSDictionary * parameters = @ { @“ foo ”:@“ bar ”氏堤,@“ baz ”:@ [@ 1沙绝,@ 2,@ 3 ]};
2.2.1 查詢字符串參數(shù)編碼
[[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格式參數(shù)編碼
[[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參數(shù)編碼
[[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 網(wǎng)絡(luò)連接管理
AFNetworkReachabilityManager用于監(jiān)視域名的可達(dá)性鼠锈,以及WWAN和WiFi網(wǎng)絡(luò)接口的地址闪檬。
- 不要用可達(dá)性來(lái)決定,是否應(yīng)該發(fā)送原始請(qǐng)求购笆。
- 你應(yīng)該嘗試發(fā)送它粗悯。
- 您可以使用可達(dá)性來(lái)決定,何時(shí)應(yīng)自動(dòng)重試請(qǐng)求同欠。
- 可達(dá)性通知(連接可用)是發(fā)起重試時(shí)間的好時(shí)機(jī)样傍,雖然它可能仍然失敗。
- 網(wǎng)絡(luò)可達(dá)性铺遂,是確定請(qǐng)求可能失敗原因的一個(gè)有用工具衫哥。
- 在網(wǎng)絡(luò)請(qǐng)求失敗之后,告訴他們離線的用戶比給予他們一個(gè)更為技術(shù)性但準(zhǔn)確的錯(cuò)誤襟锐,比如“請(qǐng)求超時(shí)”撤逢。
另見WWDC 2012會(huì)議706“網(wǎng)絡(luò)最佳實(shí)踐”。
2.3.1 共享網(wǎng)絡(luò)可達(dá)性
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
2.4 安全策略
AFSecurityPolicy用來(lái)在安全的連接上捌斧,針對(duì)固定的X.509證書和公鑰笛质,評(píng)價(jià)服務(wù)器的可靠性。
將固定SSL證書添加到您的應(yīng)用程序捞蚂,有助于防止中間人攻擊和其他漏洞。強(qiáng)烈建議跷究,涉及到敏感客戶數(shù)據(jù)或財(cái)務(wù)信息的應(yīng)用程序應(yīng)通過(guò)HTTPS路由到所有通信姓迅,配置并啟用SSL pinning。
2.4.1 允許無(wú)效的SSL證書
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager ];
manager.securityPolicy.allowInvalidCertificates = YES ; //不推薦用于生產(chǎn)
3. 單元測(cè)試
AFNetworking在Tests子目錄中包含了一套單元測(cè)試俊马。這些測(cè)試可以簡(jiǎn)單地運(yùn)行丁存,以執(zhí)行在您想要測(cè)試的平臺(tái)框架上的測(cè)試操作。
翻譯說(shuō)明:
本文翻譯自AFNetworking柴我,版權(quán)歸官方所有解寝,翻譯僅供學(xué)習(xí)用途,以上艘儒。