AFNetworking粗解(解析)

111180.png

1.官網(wǎng)文檔外加點中文注釋
AFNetworking官網(wǎng)(點擊進入)

AFNetworking翻譯注釋
Architecture(結(jié)構(gòu))
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 將通用的與服務(wù)器應(yīng)用交互的操作封裝了起來,包括了請求的創(chuàng)建肃廓,回復(fù)的序列化,網(wǎng)絡(luò)指示器的監(jiān)測香追,安全性,當(dāng)然還有請求操作的管理坦胶。

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(復(fù)雜的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 創(chuàng)建了一個管理一個NSURLSession的對象透典,基于一個指定的NSURLSessionConfiguration對象晴楔,它與以下的這些協(xié)議融合在一起(<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>,<NSURLSessionDelegate>)。
Creating a Download Task(創(chuàng)建一個下載任務(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];
Creating an Upload Task(創(chuàng)建一個上傳任務(wù))
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(創(chuàng)建一個復(fù)雜的請求峭咒,并附帶進度)
    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(創(chuàng)建一個數(shù)據(jù)任務(wù))
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字符串創(chuàng)建請求税弃,編碼參數(shù),查找字符串或者是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表單形式參數(shù)的編碼)
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
POST http://example.com/Content-Type: application/x-www-form-urlencodedfoo=bar&baz[]=1&baz[]=2&baz[]=3
JSON Parameter Encoding(查詢json參數(shù)的編碼)
[[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(監(jiān)測網(wǎng)絡(luò)管理器)
AFNetworkReachabilityManager monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.
AFNetworkReachabilityManager 監(jiān)測域名以及IP地址的暢通性则果,對于WWAN以及WiFi的網(wǎng)絡(luò)接口都管用。
Shared Network Reachability(單例形式檢測網(wǎng)絡(luò)暢通性)
[[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網(wǎng)址的暢通性就會被仔細(xì)的監(jiān)測著西壮。
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協(xié)議來處理網(wǎng)絡(luò)請求叫惊。它封裝成了一個可以令人接受的代碼形式款青。當(dāng)然AFHTTPRequestOperationManager 目前是最好的用來處理網(wǎng)絡(luò)請求的方式,但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];

2.官網(wǎng)文檔外加點中文注釋

原創(chuàng)翻譯微博(點擊可進入)

AFNetworking 2.0
AFNetworking 是當(dāng)前 iOS 和 OS X 開發(fā)中最廣泛使用的開源項目之一可都。它幫助了成千上萬叫好又叫座的應(yīng)用,也為其它出色的開源庫提供了基礎(chǔ)蚓耽。這個項目是社區(qū)里最活躍、最有影響力的項目之一旋炒,擁有 8700 個 star步悠、2200 個 fork 和 130 名貢獻者。
從各方面來看瘫镇,AFNetworking 幾乎已經(jīng)成為主流鼎兽。
但你有沒有聽說過它的新版呢? AFNetworking 2.0铣除。
這一周的 NSHipster:獨家揭曉 AFNetworking 的未來谚咬。
聲明:NSHipster 由 AFNetworking 的作者 撰寫,所以這并不是對 AFNetworking 及它的優(yōu)點的客觀看法尚粘。你能看到的是個人關(guān)于 AFNetworking 目前及未來版本的真實看法择卦。
AFNetworking 的大體思路
始于 2011 年 5 月,AFNetworking 作為一個已死的 LBS 項目中對 Apple 范例代碼的延伸郎嫁,它的成功更是由于時機秉继。彼時 ASIHTTPRequest 是網(wǎng)絡(luò)方面的主流方案,AFNetworking 的核心思路使它正好成為開發(fā)者渴求的更現(xiàn)代的方案泽铛。
NSURLConnection + NSOperation
NSURLConnection 是 Foundation URL 加載系統(tǒng)的基石尚辑。一個 NSURLConnection 異步地加載一個NSURLRequest 對象,調(diào)用 delegate 的 NSURLResponse / NSHTTPURLResponse 方法盔腔,其 NSData 被發(fā)送到服務(wù)器或從服務(wù)器讀雀懿纭月褥;delegate 還可用來處理 NSURLAuthenticationChallenge、重定向響應(yīng)瓢喉、或是決定 NSCachedURLResponse 如何存儲在共享的 NSURLCache 上吓坚。
NSOperation 是抽象類,模擬單個計算單元灯荧,有狀態(tài)礁击、優(yōu)先級、依賴等功能逗载,可以取消哆窿。
AFNetworking 的第一個重大突破就是將兩者結(jié)合。AFURLConnectionOperation 作為 NSOperation 的子類厉斟,遵循 NSURLConnectionDelegate 的方法挚躯,可以從頭到尾監(jiān)視請求的狀態(tài),并儲存請求擦秽、響應(yīng)码荔、響應(yīng)數(shù)據(jù)等中間狀態(tài)。
Blocks
iOS 4 引入的 block 和 Grand Central Dispatch 從根本上改善了應(yīng)用程序的開發(fā)過程感挥。相比于在應(yīng)用中用 delegate 亂七八糟地實現(xiàn)邏輯缩搅,開發(fā)者們可以用 block 將相關(guān)的功能放在一起。GCD 能夠輕易來回調(diào)度工作触幼,不用面對亂七八糟的線程硼瓣、調(diào)用和操作隊列。
更重要的是置谦,對于每個 request operation堂鲤,可以通過 block 自定義 NSURLConnectionDelegate 的方法(比如,通過 setWillSendRequestForAuthenticationChallengeBlock: 可以覆蓋默認(rèn)的connection:willSendRequestForAuthenticationChallenge: 方法)媒峡。
現(xiàn)在瘟栖,我們可以創(chuàng)建 AFURLConnectionOperation 并把它安排進 NSOperationQueue,通過設(shè)置NSOperation 的新屬性 completionBlock谅阿,指定操作完成時如何處理 response 和 response data(或是請求過程中遇到的錯誤)半哟。
序列化 & 驗證
更深入一些,request operation 操作也可以負(fù)責(zé)驗證 HTTP 狀態(tài)碼和服務(wù)器響應(yīng)的內(nèi)容類型奔穿,比如镜沽,對于 application/json MIME 類型的響應(yīng),可以將 NSData 序列化為 JSON 對象贱田。
從服務(wù)器加載 JSON缅茉、XML、property list 或者圖像可以抽象并類比成潛在的文件加載操作男摧,這樣開發(fā)者可以將這個過程想象成一個 promise 而不是異步網(wǎng)絡(luò)連接蔬墩。
介紹 AFNetworking 2.0
AFNetworking 勝在易于使用和可擴展之間取得的平衡译打,但也并不是沒有提升的空間。
在第二個大版本中拇颅,AFNetworking 旨在消除原有設(shè)計的怪異之處奏司,同時為下一代 iOS 和 OS X 應(yīng)用程序增加一些強大的新架構(gòu)。
動機

兼容 NSURLSession - NSURLSession 是 iOS 7 新引入的用于替代 NSURLConnection 的類樟插。NSURLConnection 并沒有被棄用韵洋,今后一段時間應(yīng)該也不會,但是 NSURLSession 是 Foundation 中網(wǎng)絡(luò)的未來黄锤,并且是一個美好的未來搪缨,因為它改進了之前的很多缺點。(參考 WWDC 2013 Session 705 “What’s New in Foundation Networking”鸵熟,一個很好的概述)副编。起初有人推測,NSURLSession 的出現(xiàn)將使 AFNetworking 不再有用流强。但實際上痹届,雖然它們有一些重疊,AFNetworking 還是可以提供更高層次的抽象打月。AFNetworking 2.0 不僅做到了這一點队腐,還借助并擴展 NSURLSession 來鋪平道路上的坑洼,并最大程度擴展了它的實用性僵控。

模塊化 - 對于 AFNetworking 的主要批評之一是笨重香到。雖然它的構(gòu)架使在類的層面上是模塊化的,但它的包裝并不允許選擇獨立的一些功能报破。隨著時間的推移,AFHTTPClient尤其變得不堪重負(fù)(其任務(wù)包括創(chuàng)建請求千绪、序列化 query string 參數(shù)充易、確定響應(yīng)解析行為、生成和管理 operation荸型、監(jiān)視網(wǎng)絡(luò)可達性)盹靴。 在 AFNetworking 2.0 中,你可以挑選并通過 CocoaPods subspecs 選擇你所需要的組件瑞妇。

實時性 - 在新版本中稿静,AFNetworking 嘗試將實時性功能提上日程。在接下來的 18 個月辕狰,實時性將從最棒的 1% 變成用戶都期待的功能改备。 AFNetworking 2.0 采用 Rocket技術(shù),利用 Server-Sent Event 和 JSON Patch 等網(wǎng)絡(luò)標(biāo)準(zhǔn)在現(xiàn)有的 REST 網(wǎng)絡(luò)服務(wù)上構(gòu)建語義上的實時服務(wù)蔓倍。

演員陣容
NSURLConnection 組件 (iOS 6 & 7)

AFURLConnectionOperation - NSOperation 的子類悬钳,負(fù)責(zé)管理 NSURLConnection 并且實現(xiàn)其 delegate 方法盐捷。

AFHTTPRequestOperation - AFURLConnectionOperation 的子類,用于生成 HTTP 請求默勾,可以區(qū)別可接受的和不可接受的狀態(tài)碼及內(nèi)容類型碉渡。2.0 版本中的最大區(qū)別是,你可以直接使用這個類母剥,而不用繼承它滞诺,原因可以在“序列化”一節(jié)中找到。

AFHTTPRequestOperationManager - 包裝常見 HTTP web 服務(wù)操作的類环疼,通過AFHTTPRequestOperation 由 NSURLConnection 支持习霹。
NSURLSession 組件 (iOS 7)

AFURLSessionManager - 創(chuàng)建、管理基于 NSURLSessionConfiguration 對象的NSURLSession 對象的類秦爆,也可以管理 session 的數(shù)據(jù)序愚、下載/上傳任務(wù),實現(xiàn) session 和其相關(guān)聯(lián)的任務(wù)的 delegate 方法等限。因為 NSURLSession API 設(shè)計中奇怪的空缺爸吮,任何和NSURLSession 相關(guān)的代碼都可以用 AFURLSessionManager 改善。

AFHTTPSessionManager - AFURLSessionManager 的子類望门,包裝常見的 HTTP web 服務(wù)操作唇聘,通過 AFURLSessionManager 由 NSURLSession 支持虾攻。

總的來說:為了支持新的 NSURLSession API 以及舊的未棄用且還有用的NSURLConnection,AFNetworking 2.0 的核心組件分成了 request operation 和 session 任務(wù)。AFHTTPRequestOperationManager 和 AFHTTPSessionManager 提供類似的功能玩般,在需要的時候(比如在 iOS 6 和 7 之間轉(zhuǎn)換),它們的接口可以相對容易的互換华糖。
之前所有綁定在 AFHTTPClient的功能难裆,比如序列化、安全性祷膳、可達性陶衅,被拆分成幾個獨立的模塊,可被基于 NSURLSession 和 NSURLConnection 的 API 使用直晨。

序列化
AFNetworking 2.0 新構(gòu)架的突破之一是使用序列化來創(chuàng)建請求搀军、解析響應(yīng)∮禄剩可以通過序列化的靈活設(shè)計將更多業(yè)務(wù)邏輯轉(zhuǎn)移到網(wǎng)絡(luò)層罩句,并更容易定制之前內(nèi)置的默認(rèn)行為。

<AFURLRequestSerializer> - 符合這個協(xié)議的對象用于處理請求敛摘,它將請求參數(shù)轉(zhuǎn)換為 query string 或是 entity body 的形式门烂,并設(shè)置必要的 header。那些不喜歡 AFHTTPClient使用 query string 編碼參數(shù)的家伙着撩,你們一定喜歡這個诅福。

<AFURLResponseSerializer> - 符合這個協(xié)議的對象用于驗證匾委、序列化響應(yīng)及相關(guān)數(shù)據(jù),轉(zhuǎn)換為有用的形式氓润,比如 JSON 對象赂乐、圖像、甚至基于 Mantle 的模型對象咖气。相比沒完沒了地繼承 AFHTTPClient挨措,現(xiàn)在 AFHTTPRequestOperation 有一個 responseSerializer 屬性,用于設(shè)置合適的 handler崩溪。同樣的浅役,再也沒有沒用的受 NSURLProtocol 啟發(fā)的 request operation 類注冊,取而代之的還是很棒的 responseSerializer 屬性伶唯。謝天謝地觉既。

安全性
感謝 Dustin Barker、Oliver Letterer乳幸、Kevin Harwood 等人做出的貢獻瞪讼,AFNetworking 現(xiàn)在帶有內(nèi)置的 SSL pinning 支持,這對于處理敏感信息的應(yīng)用是十分重要的粹断。
AFSecurityPolicy - 評估服務(wù)器對安全連接針對指定的固定證書或公共密鑰的信任符欠。tl;dr 將你的服務(wù)器證書添加到 app bundle,以幫助防止 中間人攻擊瓶埋。

可達性
從 AFHTTPClient 解藕的另一個功能是網(wǎng)絡(luò)可達性∠J粒現(xiàn)在你可以直接使用它,或者使用AFHTTPRequestOperationManager / AFHTTPSessionManager 的屬性养筒。
AFNetworkReachabilityManager - 這個類監(jiān)控當(dāng)前網(wǎng)絡(luò)的可達性曾撤,提供回調(diào) block 和 notificaiton,在可達性變化時調(diào)用晕粪。

實時性
AFEventSource - EventSource DOM API 的 Objective-C 實現(xiàn)盾戴。建立一個到某主機的持久 HTTP 連接,可以將事件傳輸?shù)绞录床⑴砂l(fā)到聽眾兵多。傳輸?shù)绞录吹南⒌母袷綖镴SON Patch 文件,并被翻譯成 AFJSONPatchOperation 對象的數(shù)組橄仆∈1欤可以將這些 patch operation 應(yīng)用到之前從服務(wù)器獲取的持久性數(shù)據(jù)集。

{objective-c} NSURL *URL = [NSURL URLWithString:@"http://example.com"]; AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL]; [manager GET:@"/resources" parameters:nil success:NSURLSessionDataTask *task, id responseObject { [resources addObjectsFromArray:responseObject[@"resources"]];

[manager SUBSCRIBE:@"/resources" usingBlock:NSArray *operations, NSError *error { for (AFJSONPatchOperation *operation in operations) { 
switch (operation.type) { 
case AFJSONAddOperationType: [resources addObject:operation.value]; break; default: break;
 } }
 } error:nil]; 
} failure:nil]; 

UIKit 擴展
`
之前 AFNetworking 中的所有 UIKit category 都被保留并增強盆顾,還增加了一些新的 category怠褐。

AFNetworkActivityIndicatorManager:在請求操作開始、停止加載時您宪,自動開始奈懒、停止?fàn)顟B(tài)欄上的網(wǎng)絡(luò)活動指示圖標(biāo)奠涌。

UIImageView+AFNetworking:增加了 imageResponseSerializer 屬性,可以輕松地讓遠程加載到 image view 上的圖像自動調(diào)整大小或應(yīng)用濾鏡磷杏。比如溜畅,AFCoreImageSerializer可以在 response 的圖像顯示之前應(yīng)用 Core Image filter。

UIButton+AFNetworking (新):與 UIImageView+AFNetworking 類似极祸,從遠程資源加載image 和 backgroundImage慈格。

UIActivityIndicatorView+AFNetworking (新):根據(jù)指定的請求操作和會話任務(wù)的狀態(tài)自動開始、停止 UIActivityIndicatorView遥金。

UIProgressView+AFNetworking (新):自動跟蹤某個請求或會話任務(wù)的上傳/下載進度浴捆。
UIWebView+AFNetworking (新): 為加載 URL 請求提供了更強大的API,支持進度回調(diào)和內(nèi)容轉(zhuǎn)換稿械。
`

于是終于要結(jié)束 AFNetworking 旋風(fēng)之旅了选泻。為下一代應(yīng)用設(shè)計的新功能,結(jié)合為已有功能設(shè)計的全新架構(gòu)美莫,有很多東西值得興奮页眯。
旗開得勝
將下列代碼加入 Podfile 就可以開始把玩 AFNetworking 2.0 了:
platform :ios, '7.0'pod "AFNetworking", "2.0.0"

3.中文詳細(xì)解析
(點擊進入)
AFNetworking2.0源碼解析<一>
AFNetworking2.0源碼解析<二>
AFNetworking2.0源碼解析<三>

4.源代碼

可以下載的URL:

#define Pictureurl @"http://x1.zhuti.com/down/2012/11/29-win7/3D-1.jpg"
#define imagurl @"http://pic.cnitblog.com/avatar/607542/20140226182241.png"
#define Musicurl @"http://bcs.duapp.com/chenwei520/media/music.mp3"
#define Zipurl @"http://example.com/download.zip"
#define Jsonurl @"https://api.douban.com/v2/movie/us_box"
#define Xmlurl @"http://flash.weather.com.cn/wmaps/xml/beijing.xml"
#define Movieurl @"http://bcs.duapp.com/chenwei520/media/mobile_vedio.mp4"

interface中需要創(chuàng)建的UI
[objc] view plaincopyprint?

1.  <pre name="code" class="objc">@interface ViewController () 
2.  
3.  @end 
4.  
5.  @implementation ViewController{ 
6.  
7.  UIProgressView *_progressView; 
8.  UIActivityIndicatorView *_activitView; 
9.  AFURLSessionManager *SessionManage; 
10. 
11. } 
12. 
13. - (void)viewDidLoad 
14. { 
15. [super viewDidLoad]; 
16. _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; 
17. _progressView.frame = CGRectMake(0,100,320,20); 
18. _progressView.tag = 2014; 
19. _progressView.progress = 0.0; 
20. [self.view addSubview:_progressView]; 
21. 
22. _activitView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
23. _activitView.frame = CGRectMake(160, 140, 0, 0); 
24. _activitView.backgroundColor = [UIColor yellowColor]; 
25. [self.view addSubview:_activitView]; 
26. 
27. //添加下載任務(wù) 
28. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
29. button.frame = CGRectMake(140, 60, 40, 20); 
30. [button setTitle:@"下載" forState:UIControlStateNormal]; 
31. button.backgroundColor = [UIColor orangeColor]; 
32. 
33. [button addTarget:self action:@selector(addDownloadTask:) forControlEvents:UIControlEventTouchUpInside]; 
34. [self.view addSubview:button]; 
<pre name="code" class="objc">@interface ViewController ()@end@implementation ViewController{    UIProgressView *_progressView;    UIActivityIndicatorView *_activitView;    AFURLSessionManager *SessionManage;}- (void)viewDidLoad{    [super viewDidLoad];    _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];    _progressView.frame = CGRectMake(0,100,320,20);    _progressView.tag = 2014;    _progressView.progress = 0.0;    [self.view addSubview:_progressView];        _activitView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];    _activitView.frame = CGRectMake(160, 140, 0, 0);    _activitView.backgroundColor = [UIColor yellowColor];    [self.view addSubview:_activitView];        //添加下載任務(wù)    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];    button.frame = CGRectMake(140, 60, 40, 20);    [button setTitle:@"下載" forState:UIControlStateNormal];    button.backgroundColor = [UIColor orangeColor];        [button addTarget:self action:@selector(addDownloadTask:) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:button];

//AFHTTPRequestOperationManager無參數(shù)的GET請求(成功)
[objc] view plaincopyprint?

1.  - (void)GETTask1{//下載成功 
2.  
3.  NSString *url = Musicurl; 
4.  
5.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
6.  
7.  manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不對數(shù)據(jù)解析 
8.  
9.  //無參數(shù)的GET請求下載parameters:nil,也可以帶參數(shù) 
10. AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { 
11. 
12. //下載完成后打印這個 
13. NSLog(@"下載完成"); 
14. 
15. _progressView.hidden = YES; 
16. 
17. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
18. 
19. NSLog(@"下載失敗"); 
20. 
21. }]; 
22. 
23. //定義下載路徑 
24. NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[url lastPathComponent]]; 
25. 
26. NSLog(@"%@",filePath); 
27. 
28. ///Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/music.mp3 
29. 
30. //創(chuàng)建下載文件 
31. if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
32. 
33. //會自動將數(shù)據(jù)寫入文件 
34. [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; 
35. 
36. } 
37. 
38. //加載進度視圖 
39. [_activitView setAnimatingWithStateOfOperation:operation]; 
40. 
41. //使用AF封裝好的類目UIProgressView+AFNetworking.h 
42. if (operation != nil) { 
43. //下載進度 
44. [_progressView setProgressWithDownloadProgressOfOperation:operation animated:YES]; 
45. } 
46. 
47. //設(shè)置下載的輸出流,而此輸出流寫入文件,這里可以計算傳輸文件的大小 
48. operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES]; 
49. 
50. __weak ViewController *weakSelf = self; 
51. 
52. //監(jiān)聽的下載的進度 
53. /* 
54. * 
55. * bytesRead 每次傳輸?shù)臄?shù)據(jù)包大小 
56. * totalBytesRead 已下載的數(shù)據(jù)大小 
57. * totalBytesExpectedToRead 總大小 
58. * 
59. */ 
60. 
61. //調(diào)用Block監(jiān)聽下載傳輸情況 
62. [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 
63. 
64. CGFloat progess = totalBytesRead/(CGFloat)totalBytesExpectedToRead; 
65. 
66. __strong ViewController *strongSelf = weakSelf; 
67. 
68. strongSelf->_progressView.progress = progess; 
69. 
70. }]; 
71. 
72. } 
- (void)GETTask1{//下載成功        NSString *url = Musicurl;        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];        manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不對數(shù)據(jù)解析        //無參數(shù)的GET請求下載parameters:nil,也可以帶參數(shù)    AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {                //下載完成后打印這個        NSLog(@"下載完成");                _progressView.hidden = YES;            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                NSLog(@"下載失敗");            }];        //定義下載路徑    NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[url lastPathComponent]];        NSLog(@"%@",filePath);        ///Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/music.mp3        //創(chuàng)建下載文件    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {                //會自動將數(shù)據(jù)寫入文件        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];            }        //加載進度視圖    [_activitView setAnimatingWithStateOfOperation:operation];        //使用AF封裝好的類目UIProgressView+AFNetworking.h    if (operation != nil) {        //下載進度        [_progressView setProgressWithDownloadProgressOfOperation:operation animated:YES];    }        //設(shè)置下載的輸出流茂嗓,而此輸出流寫入文件,這里可以計算傳輸文件的大小    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];        __weak ViewController *weakSelf = self;        //監(jiān)聽的下載的進度    /*     *     * bytesRead                每次傳輸?shù)臄?shù)據(jù)包大小     * totalBytesRead           已下載的數(shù)據(jù)大小     * totalBytesExpectedToRead 總大小     *     */        //調(diào)用Block監(jiān)聽下載傳輸情況    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {                CGFloat progess = totalBytesRead/(CGFloat)totalBytesExpectedToRead;                __strong ViewController *strongSelf = weakSelf;                strongSelf->_progressView.progress = progess;            }];    }

//AFHTTPRequestOperationManager附帶表單編碼的POST請求-------URL-Form-Encoded(成功)

[objc] view plaincopyprint?

1.  - (void)POSTTask1{//發(fā)送微博成功 
2.  
3.  NSMutableDictionary *params = [NSMutableDictionary dictionary]; 
4.  [params setValue:@"正在發(fā)微博" forKey:@"status"];//發(fā)送微博的類容 
5.  [params setValue:@"xxxxxx" forKey:@"access_token"];//XXXXX自己注冊新浪微博開發(fā)賬號得到的令牌 
6.  
7.  NSString *urlstring = @"https://api.weibo.com/2/statuses/updata.json"; 
8.  
9.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
10. AFHTTPRequestOperation *operation = nil; 
11. 
12. operation = [manager POST:urlstring parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
13. 
14. NSLog(@"發(fā)送成功:%@",responseObject); 
15. 
16. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
17. 
18. NSLog(@"網(wǎng)絡(luò)請求失敳鸵稹:%@",error); 
19. 
20. }]; 
21. 
22. } 
- (void)POSTTask1{//發(fā)送微博成功    NSMutableDictionary *params = [NSMutableDictionary dictionary];    [params setValue:@"正在發(fā)微博" forKey:@"status"];//發(fā)送微博的類容    [params setValue:@"xxxxxx" forKey:@"access_token"];//XXXXX自己注冊新浪微博開發(fā)賬號得到的令牌        NSString *urlstring = @"https://api.weibo.com/2/statuses/updata.json";        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    AFHTTPRequestOperation *operation = nil;        operation = [manager POST:urlstring parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {                NSLog(@"發(fā)送成功:%@",responseObject);            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                NSLog(@"網(wǎng)絡(luò)請求失敗:%@",error);            }];}

//AFHTTPRequestOperationManager復(fù)雜的POST請求--------Multi-Part(成功)

[objc] view plaincopyprint?

1.  - (void)POSTTask2{ 
2.  
3.  //file://本地文件傳輸協(xié)議,file:// + path就是完整路徑,可以用瀏覽器打開 
4.  //file:///Users/mac1/Desktop/whrite.png 
5.  
6.  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
7.  AFHTTPRequestOperation *operation = nil; 
8.  
9.  NSMutableDictionary *params = [NSMutableDictionary dictionary]; 
10. [params setValue:@"帶圖片哦" forKey:@"status"]; 
11. [params setValue:@"XXXXXX" forKey:@"access_token"]; 
12. 
13. 
14. //方式一(拖到編譯器中的圖片) 
15. //UIImage *_sendImg = [UIImage imageNamed:@"whrite.png"]; 
16. //NSData *data = UIImageJPEGRepresentation(_sendImg, 1); 
17. //NSData *data = UIImagePNGRepresentation(_sendImg); 
18. 
19. //方式二(程序包中的圖片) 
20. //NSString *theImagePath = [[NSBundle mainBundle] pathForResource:@"whrite"ofType:@"png"];//文件包路徑,在程序包中 
21. //NSURL *Imagefile = [NSURL fileURLWithPath:theImagePath]; 
22. 
23. //方式三,沙盒中的圖片 
24. NSString *pathstring = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/whrite.png"];//從沙盒中找到文件,沙盒中需要有這個whrite.png圖片 
25. NSURL *urlfile = [NSURL fileURLWithPath:pathstring]; 
26. 
27. operation = [manager POST:@"https://api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {//multipart/form-data編碼方式 
28. 
29. //方式二和三調(diào)用的方法,給的是URL 
30. [formData appendPartWithFileURL:urlfile name:@"pic" error:nil];//name:@"pic"新浪微博要求的名字,去閱讀新浪的API文檔 
31. 
32. //方式三調(diào)用的方法,給的是Data 
33. //[formData appendPartWithFileData:data name:@"pic" fileName:@"pic" mimeType:@"image/png"]; 
34. 
35. 
36. } success:^(AFHTTPRequestOperation *operation, id responseObject) { 
37. NSLog(@"Success: %@", responseObject); 
38. 
39. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
40. NSLog(@"Error: %@", error); 
41. }]; 
42. 
43. //監(jiān)聽進度 
44. [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
45. 
46. CGFloat progress = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite; 
47. NSLog(@"進度:%.1f",progress); 
48. 
49. }]; 
50. 
51. } 
- (void)POSTTask2{      
  //file://本地文件傳輸協(xié)議,
file:// + path就是完整路徑,可以用瀏覽器打開    
//file:///Users/mac1/Desktop/whrite.png        
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
   AFHTTPRequestOperation *operation = nil;       
 NSMutableDictionary *params = [NSMutableDictionary dictionary];   
 [params setValue:@"帶圖片哦" forKey:@"status"];    [params setValue:@"XXXXXX" forKey:@"access_token"];           
 //方式一(拖到編譯器中的圖片)   
 //UIImage *_sendImg = [UIImage imageNamed:@"whrite.png"];   
 //NSData *data = UIImageJPEGRepresentation(_sendImg, 1);    
//NSData *data = UIImagePNGRepresentation(_sendImg);       
//方式二(程序包中的圖片)    
//NSString *theImagePath = [[NSBundle mainBundle] pathForResource:@"whrite"ofType:@"png"];
//文件包路徑,在程序包中     
//NSURL *Imagefile = [NSURL fileURLWithPath:theImagePath];      
 //方式三,沙盒中的圖片   
 NSString *pathstring = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/whrite.png"];
//從沙盒中找到文件,沙盒中需要有這個whrite.png圖片    
NSURL *urlfile = [NSURL fileURLWithPath:pathstring];       
 operation = [manager POST:@"https://api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//multipart/form-data編碼方式               
 //方式二和三調(diào)用的方法,給的是URL      
  [formData appendPartWithFileURL:urlfile name:@"pic" error:nil];
//name:@"pic"新浪微博要求的名字,去閱讀新浪的API文檔             
   //方式三調(diào)用的方法,給的是Data      
 //[formData appendPartWithFileData:data name:@"pic" fileName:@"pic" mimeType:@"image/png"];           
 } success:^(AFHTTPRequestOperation *operation, id responseObject) {       
 NSLog(@"Success: %@", responseObject);          
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {       
 NSLog(@"Error: %@", error);    }];        
//監(jiān)聽進度  
  [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {                
CGFloat progress = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite;        
NSLog(@"進度:%.1f",progress);            }];  
 }

//AFHTTPRequestOperation(構(gòu)建request,使用setCompletionBlockWithSuccess)(成功)
[objc] view plaincopyprint?

1.  - (void)SimpleGETTaskOperation{//使用AFHTTPRequestOperation,不帶參數(shù),無需指定請求的類型 
2.  
3.  NSURL *URL = [NSURL URLWithString:Pictureurl]; 
4.  
5.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
6.  
7.  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
8.  
9.  // 進行操作的配置,設(shè)置解析序列化方式 
10. 
11. //Json 
12. //op.responseSerializer = [AFJSONResponseSerializer serializer]; 
13. //op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers]; 
14. 
15. //Image 
16. operation.responseSerializer = [AFImageResponseSerializer serializer]; 
17. 
18. //XML 
19. //operation.responseSerializer = [AFXMLParserResponseSerializer serializer]; 
20. 
21. [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
22. 
23. NSLog(@"responseObject = %@", responseObject);//返回的是對象類型 
24. 
25. } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
26. NSLog(@"Error: %@", error); 
27. }]; 
28. 
29. //[[NSOperationQueue mainQueue] addOperation:operation]; 
30. [operation start]; 
31. 
32. } 
- (void)SimpleGETTaskOperation{
//使用AFHTTPRequestOperation,不帶參數(shù),無需指定請求的類型       
 NSURL *URL = [NSURL URLWithString:Pictureurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];     
   AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];       
 // 進行操作的配置,設(shè)置解析序列化方式      
  //Json    
//op.responseSerializer = [AFJSONResponseSerializer serializer];  
 //op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];        
//Image   
 operation.responseSerializer = [AFImageResponseSerializer serializer];     
   //XML   
 //operation.responseSerializer = [AFXMLParserResponseSerializer serializer];     
  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {               
NSLog(@"responseObject = %@", responseObject);//返回的是對象類型           
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {       
NSLog(@"Error: %@", error);    }];      
  //[[NSOperationQueue mainQueue] addOperation:operation];   
 [operation start];  
  }

//AFHTTPRequestOperation(許多操作一起進行)(未成功)
[objc] view plaincopyprint?

1.  - (void)CompleTaskOperation{ 
2.  
3.  NSMutableArray *mutableOperations = [NSMutableArray array]; 
4.  
5.  NSArray *filesToUpload = nil; 
6.  for (NSURL *fileURL in filesToUpload) { 
7.  
8.  NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
9.  
10. [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil]; 
11. }]; 
12. 
13. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
14. 
15. [mutableOperations addObject:operation]; 
16. } 
17. 
18. NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[@"一個",@"兩個"] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { 
19. 
20. NSLog(@"%lu of %lu complete", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations); 
21. 
22. } completionBlock:^(NSArray *operations) { 
23. 
24. NSLog(@"All operations in batch complete"); 
25. }]; 
26. 
27. [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO]; 
28. 
29. } 
- (void)CompleTaskOperation{   
 NSMutableArray *mutableOperations = [NSMutableArray array];       
 NSArray *filesToUpload = nil;   
 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", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations);           
 } completionBlock:^(NSArray *operations) {               
 NSLog(@"All operations in batch complete");    }];       
 [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}

//創(chuàng)建一個下載任務(wù)---------downloadTaskWithRequest(成功)
[objc] view plaincopyprint?

1.  - (void)DownloadTask{//下載成功 
2.  
3.  // 定義一個progress指針 
4.  NSProgress *progress = nil; 
5.  
6.  // 創(chuàng)建一個URL鏈接 
7.  NSURL *url = [NSURL URLWithString:Pictureurl]; 
8.  
9.  // 初始化一個請求 
10. NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
11. 
12. // 獲取一個Session管理器 
13. AFHTTPSessionManager *session = [AFHTTPSessionManager manager]; 
14. 
15. // 開始下載任務(wù) 
16. NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) 
17. { 
18. // 拼接一個文件夾路徑 
19. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
20. 
21. NSLog(@"不完整路徑%@",documentsDirectoryURL); 
22. //下載成后的路徑,這個路徑在自己電腦上的瀏覽器能打開 
23. //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/ 
24. 
25. // 根據(jù)網(wǎng)址信息拼接成一個完整的文件存儲路徑并返回給block 
26. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 
27. 
28. //----------可與寫入沙盒中------------- 
29. 
30. 
31. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) 
32. { 
33. // 結(jié)束后移除掉這個progress 
34. [progress removeObserver:self 
35. forKeyPath:@"fractionCompleted" 
36. context:NULL]; 
37. }]; 
38. 
39. // 設(shè)置這個progress的唯一標(biāo)示符 
40. [progress setUserInfoObject:@"someThing" forKey:@"Y.X."]; 
41. 
42. [downloadTask resume]; 
43. 
44. // 給這個progress添加監(jiān)聽任務(wù) 
45. [progress addObserver:self 
46. forKeyPath:@"fractionCompleted" 
47. options:NSKeyValueObservingOptionNew 
48. context:NULL]; 
49. } 
50. //監(jiān)聽進度的方法(沒調(diào)用) 
51. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context 
52. { 
53. if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) { 
54. NSProgress *progress = (NSProgress *)object; 
55. NSLog(@"Progress is %f", progress.fractionCompleted); 
56. 
57. // 打印這個唯一標(biāo)示符 
58. NSLog(@"%@", progress.userInfo); 
59. } 
60. } 
- (void)DownloadTask{
//下載成功       
 // 定義一個progress指針    
NSProgress *progress = nil;        
// 創(chuàng)建一個URL鏈接    
NSURL *url = [NSURL URLWithString:Pictureurl];        
// 初始化一個請求    
NSURLRequest *request = [NSURLRequest requestWithURL:url];       
 // 獲取一個Session管理器    
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];        
// 開始下載任務(wù)    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)        {                                                 
// 拼接一個文件夾路徑                                                  
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];                                                                                                    NSLog(@"不完整路徑%@",documentsDirectoryURL);                                                  
//下載成后的路徑,這個路徑在自己電腦上的瀏覽器能打開                                                  //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/                                                                                                    // 根據(jù)網(wǎng)址信息拼接成一個完整的文件存儲路徑并返回給block                                                  
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];                                                                                                   
 //----------可與寫入沙盒中-------------                                                                                                                                                  } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)                                              {                                                  
// 結(jié)束后移除掉這個progress                                                  
[progress removeObserver:self                                                                forKeyPath:@"fractionCompleted"         context:NULL];                                 
             }];        
// 設(shè)置這個progress的唯一標(biāo)示符   
 [progress setUserInfoObject:@"someThing" forKey:@"Y.X."];        
[downloadTask resume];      
  // 給這個progress添加監(jiān)聽任務(wù)   
 [progress addObserver:self               forKeyPath:@"fractionCompleted"                  options:NSKeyValueObservingOptionNew                  context:NULL];}
//監(jiān)聽進度的方法(沒調(diào)用)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{    
if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {      
  NSProgress *progress = (NSProgress *)object;      
 NSLog(@"Progress is %f", progress.fractionCompleted);                
// 打印這個唯一標(biāo)示符        
NSLog(@"%@", progress.userInfo);   
 }}

//AFURLSessionManager下載隊列,且能在后臺下載,關(guān)閉了應(yīng)用后還繼續(xù)下載(成功)
[objc] view plaincopyprint?

1.  - (void)DownloadTaskbackaAndqueue{ 
2.  
3.  // 配置后臺下載會話配置 
4.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"]; 
5.  
6.  // 初始化SessionManager管理器 
7.  SessionManage = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
8.  
9.  // 獲取添加到該SessionManager管理器中的下載任務(wù) 
10. NSArray *downloadTasks = [SessionManage downloadTasks]; 
11. 
12. // 如果有下載任務(wù) 
13. if (downloadTasks.count) 
14. { 
15. NSLog(@"downloadTasks: %@", downloadTasks); 
16. 
17. // 繼續(xù)全部的下載鏈接 
18. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) 
19. { 
20. [downloadTask resume]; 
21. } 
22. } 
23. } 
24. 
25. //點擊按鈕添加下載任務(wù) 
26. - (void)addDownloadTask:(id)sender 
27. { 
28. // 組織URL 
29. NSURL *URL = [NSURL URLWithString:imagurl]; 
30. 
31. // 組織請求 
32. NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
33. 
34. // 給SessionManager管理器添加一個下載任務(wù) 
35. NSURLSessionDownloadTask *downloadTask = 
36. [SessionManage downloadTaskWithRequest:request 
37. progress:nil 
38. destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
39. 
40. //下載文件路徑 
41. NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]; 
42. return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]]; 
43. 
44. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
45. NSLog(@"File downloaded to: %@", filePath); 
46. 
47. //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/CFNetworkDownload_NWLWU6.tmp 
48. 
49. }]; 
50. [downloadTask resume]; 
51. 
52. // 打印下載的標(biāo)示 
53. NSLog(@"%d", downloadTask.taskIdentifier); 
54. } 
- (void)DownloadTaskbackaAndqueue{       
 // 配置后臺下載會話配置    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"];        
// 初始化SessionManager管理器    
SessionManage = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        // 獲取添加到該SessionManager管理器中的下載任務(wù)    
NSArray *downloadTasks = [SessionManage downloadTasks];       
 // 如果有下載任務(wù)  
  if (downloadTasks.count)    {       
 NSLog(@"downloadTasks: %@", downloadTasks);                
// 繼續(xù)全部的下載鏈接       
 for (NSURLSessionDownloadTask *downloadTask in downloadTasks)  {        
    [downloadTask resume];    
    }  
  }}

//點擊按鈕添加下載任務(wù)

- (void)addDownloadTask:(id)sender{    
// 組織URL   
 NSURL *URL = [NSURL URLWithString:imagurl];        
// 組織請求    
NSURLRequest *request = [NSURLRequest requestWithURL:URL];        
// 給SessionManager管理器添加一個下載任務(wù)    
NSURLSessionDownloadTask *downloadTask =    [SessionManage downloadTaskWithRequest:request      progress:nil     destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {                                                                     
//下載文件路徑                                
   NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];                                   
return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];            
   } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {                                   NSLog(@"File downloaded to: %@", filePath);                                                                      //file:///Users/mac1/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/CFNetworkDownload_NWLWU6.tmp                                                                  }];   
 [downloadTask resume];        
// 打印下載的標(biāo)示    
NSLog(@"%d", downloadTask.taskIdentifier);
}

//創(chuàng)建一個數(shù)據(jù)任務(wù)(成功)

[objc] view plaincopyprint?
1.  - (void)GreatDataTask{//下載成功 
2.  
3.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
4.  
5.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
6.  
7.  NSURL *URL = [NSURL URLWithString:Jsonurl]; 
8.  
9.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
10. 
11. //創(chuàng)建一個數(shù)據(jù)任務(wù) 
12. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
13. if (error) { 
14. NSLog(@"Error: %@", error); 
15. } else { 
16. //能將Json數(shù)據(jù)打印出來 
17. NSLog(@"*************** response = %@ \n************** responseObject = %@", response, responseObject); 
18. } 
19. }]; 
20. [dataTask resume]; 
21. 
22. } 
- (void)GreatDataTask{
//下載成功    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];       
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        
NSURL *URL = [NSURL URLWithString:Jsonurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];      
  //創(chuàng)建一個數(shù)據(jù)任務(wù)   
 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {        
if (error) {           
 NSLog(@"Error: %@", error);       
 } else {            
//能將Json數(shù)據(jù)打印出來            
NSLog(@"*************** response = %@ \n************** responseObject = %@", response, responseObject);       
 }   
 }];  
  [dataTask resume];   
 }

//創(chuàng)建一個上傳的任務(wù)(尚未成功)

[objc] view plaincopyprint?
1.  - (void)UploadTask{ 
2.  
3.  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
4.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 
5.  
6.  NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; 
7.  NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
8.  
9.  NSURL *filePath = [NSURL fileURLWithPath:@"/Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/whrite.png"];//給的是沙盒路徑下的圖片 
10. 
11. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
12. if (error) { 
13. NSLog(@"Error: %@", error); 
14. } else { 
15. NSLog(@"Success: %@ %@", response, responseObject); 
16. } 
17. }]; 
18. [uploadTask resume]; 
19. 
20. } 
- (void)UploadTask{    
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:@"/Users/mac1/Library/Application Support/iPhone Simulator/7.1/Applications/787B2D0B-A400-4177-9914-25DA7F40A54B/Documents/whrite.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];
}

//創(chuàng)建一個復(fù)雜的請求(尚未成功)

[objc] view plaincopyprint?
1.  - (void)GreatComplexTask{ 
2.  
3.  NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
4.  [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 
5.  } error:nil]; 
6.  
7.  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
8.  NSProgress *progress = nil; 
9.  
10. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
11. if (error) { 
12. NSLog(@"Error: %@", error); 
13. } else { 
14. NSLog(@"%@ %@", response, responseObject); 
15. } 
16. }]; 
17. 
18. [uploadTask resume]; 
19. 
20. }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末述吸,一起剝皮案震驚了整個濱河市忿族,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蝌矛,老刑警劉巖道批,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異入撒,居然都是意外死亡隆豹,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門茅逮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來璃赡,“玉大人,你說我怎么就攤上這事献雅〉锟迹” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵挺身,是天一觀的道長侯谁。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么墙贱? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任热芹,我火速辦了婚禮,結(jié)果婚禮上惨撇,老公的妹妹穿的比我還像新娘伊脓。我一直安慰自己,他們只是感情好串纺,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布丽旅。 她就那樣靜靜地躺著,像睡著了一般纺棺。 火紅的嫁衣襯著肌膚如雪榄笙。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天祷蝌,我揣著相機與錄音茅撞,去河邊找鬼。 笑死巨朦,一個胖子當(dāng)著我的面吹牛米丘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播糊啡,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拄查,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了棚蓄?” 一聲冷哼從身側(cè)響起堕扶,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎梭依,沒想到半個月后稍算,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡役拴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年糊探,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片河闰。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡科平,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出姜性,到底是詐尸還是另有隱情匠抗,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布污抬,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏印机。R本人自食惡果不足惜矢腻,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望射赛。 院中可真熱鬧多柑,春花似錦、人聲如沸楣责。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽秆麸。三九已至初嘹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間沮趣,已是汗流浹背屯烦。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留房铭,地道東北人驻龟。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像缸匪,于是被迫代替她去往敵國和親翁狐。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 在蘋果徹底棄用NSURLConnection之后自己總結(jié)的一個網(wǎng)上的內(nèi)容凌蔬,加上自己寫的小Demo露懒,很多都是借鑒網(wǎng)絡(luò)...
    付寒宇閱讀 4,283評論 2 13
  • 二、 詳細(xì)介紹 1. AFNetworking 這是 AFNetworking 的主要部分龟梦,包括 6 個功能部分共...
    隨風(fēng)飄蕩的小逗逼閱讀 4,418評論 0 2
  • AFN什么是AFN全稱是AFNetworking隐锭,是對NSURLConnection、NSURLSession的一...
    醉葉惜秋閱讀 1,201評論 0 0
  • 同步請求和異步請求- 同步請求:阻塞式請求计贰,會導(dǎo)致用戶體驗的中斷- 異步請求:非阻塞式請求钦睡,不中斷用戶體驗,百度地...
    WangDavid閱讀 589評論 0 0
  • 今天有個小姑娘送了我一個娃娃躁倒,我很開心這是一種溫暖的感覺 其實我們并...
    聽誰在唱閱讀 170評論 0 0