AFNetworking官網文檔及翻譯

AFNetworking2.4.1解析
1.官網文檔外加點中文註釋
AFNetworking官網(點擊進入)

AFNetworking翻譯註釋
Architecture(結構)
NSURLConnection
• AFURLConnectionOperation
• AFHTTPRequestOperation
• AFHTTPRequestOperationManager
NSURLSession (iOS 7 / Mac OS X 10.9)
• AFURLSessionManager
• AFHTTPSessionManager
Serialization(序列化)

• AFHTTPRequestSerializer
• AFJSONRequestSerializer
• AFPropertyListRequestSerializer

• 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 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 , , , and .
AFURLSessionManager 創建了一個管理一個NSURLSession的對象,基於一個指定的NSURLSessionConfiguration對象,它與以下的這些協議融合在一起(, , ,)。
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 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 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.官網文檔外加點中文註釋

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

AFNetworking 2.0
AFNetworking 是當前 iOS 和 OS X 開發中最廣泛使用的開源項目之一。它幫助了成千上萬叫好又叫座的應用,也爲其它出色的開源庫提供了基礎。這個項目是社區裏最活躍、最有影響力的項目之一,擁有 8700 個 star、2200 個 fork 和 130 名貢獻者。
從各方面來看,AFNetworking 幾乎已經成爲主流。
但你有沒有聽說過它的新版呢? AFNetworking 2.0。
這一週的 NSHipster:獨家揭曉 AFNetworking 的未來。
聲明:NSHipster 由 AFNetworking 的作者 撰寫,所以這並不是對 AFNetworking 及它的優點的客觀看法。你能看到的是個人關於 AFNetworking 目前及未來版本的真實看法。
AFNetworking 的大體思路
始於 2011 年 5 月,AFNetworking 作爲一個已死的 LBS 項目中對 Apple 範例代碼的延伸,它的成功更是由於時機。彼時 ASIHTTPRequest 是網絡方面的主流方案,AFNetworking 的核心思路使它正好成爲開發者渴求的更現代的方案。
NSURLConnection + NSOperation
NSURLConnection 是 Foundation URL 加載系統的基石。一個 NSURLConnection 異步地加載一個NSURLRequest 對象,調用 delegate 的 NSURLResponse / NSHTTPURLResponse 方法,其 NSData 被髮送到服務器或從服務器讀取;delegate 還可用來處理 NSURLAuthenticationChallenge、重定向響應、或是決定 NSCachedURLResponse 如何存儲在共享的 NSURLCache 上。
NSOperation 是抽象類,模擬單個計算單元,有狀態、優先級、依賴等功能,可以取消。
AFNetworking 的第一個重大突破就是將兩者結合。AFURLConnectionOperation 作爲 NSOperation 的子類,遵循 NSURLConnectionDelegate 的方法,可以從頭到尾監視請求的狀態,並儲存請求、響應、響應數據等中間狀態。
Blocks
iOS 4 引入的 block 和 Grand Central Dispatch 從根本上改善了應用程序的開發過程。相比於在應用中用 delegate 亂七八糟地實現邏輯,開發者們可以用 block 將相關的功能放在一起。GCD 能夠輕易來回調度工作,不用面對亂七八糟的線程、調用和操作隊列。
更重要的是,對於每個 request operation,可以通過 block 自定義 NSURLConnectionDelegate 的方法(比如,通過 setWillSendRequestForAuthenticationChallengeBlock: 可以覆蓋默認的connection:willSendRequestForAuthenticationChallenge: 方法)。
現在,我們可以創建 AFURLConnectionOperation 並把它安排進 NSOperationQueue,通過設置NSOperation 的新屬性 completionBlock,指定操作完成時如何處理 response 和 response data(或是請求過程中遇到的錯誤)。
序列化 & 驗證
更深入一些,request operation 操作也可以負責驗證 HTTP 狀態碼和服務器響應的內容類型,比如,對於 application/json MIME 類型的響應,可以將 NSData 序列化爲 JSON 對象。
從服務器加載 JSON、XML、property list 或者圖像可以抽象並類比成潛在的文件加載操作,這樣開發者可以將這個過程想象成一個 promise 而不是異步網絡連接。
介紹 AFNetworking 2.0
AFNetworking 勝在易於使用和可擴展之間取得的平衡,但也並不是沒有提升的空間。
在第二個大版本中,AFNetworking 旨在消除原有設計的怪異之處,同時爲下一代 iOS 和 OS X 應用程序增加一些強大的新架構。
動機

兼容 NSURLSession - NSURLSession 是 iOS 7 新引入的用於替代 NSURLConnection 的類。NSURLConnection 並沒有被棄用,今後一段時間應該也不會,但是 NSURLSession 是 Foundation 中網絡的未來,並且是一個美好的未來,因爲它改進了之前的很多缺點。(參考 WWDC 2013 Session 705 “What’s New in Foundation Networking”,一個很好的概述)。起初有人推測,NSURLSession 的出現將使 AFNetworking 不再有用。但實際上,雖然它們有一些重疊,AFNetworking 還是可以提供更高層次的抽象。AFNetworking 2.0 不僅做到了這一點,還藉助並擴展 NSURLSession 來鋪平道路上的坑窪,並最大程度擴展了它的實用性。


模塊化 - 對於 AFNetworking 的主要批評之一是笨重。雖然它的構架使在類的層面上是模塊化的,但它的包裝並不允許選擇獨立的一些功能。隨着時間的推移,AFHTTPClient尤其變得不堪重負(其任務包括創建請求、序列化 query string 參數、確定響應解析行爲、生成和管理 operation、監視網絡可達性)。 在 AFNetworking 2.0 中,你可以挑選並通過 CocoaPods subspecs 選擇你所需要的組件。


實時性 - 在新版本中,AFNetworking 嘗試將實時性功能提上日程。在接下來的 18 個月,實時性將從最棒的 1% 變成用戶都期待的功能。 AFNetworking 2.0 採用 Rocket技術,利用 Server-Sent Event 和 JSON Patch 等網絡標準在現有的 REST 網絡服務上構建語義上的實時服務。

演員陣容
NSURLConnection 組件 (iOS 6 & 7)
• AFURLConnectionOperation - NSOperation 的子類,負責管理 NSURLConnection 並且實現其 delegate 方法。
• AFHTTPRequestOperation - AFURLConnectionOperation 的子類,用於生成 HTTP 請求,可以區別可接受的和不可接受的狀態碼及內容類型。2.0 版本中的最大區別是,你可以直接使用這個類,而不用繼承它,原因可以在“序列化”一節中找到。
• AFHTTPRequestOperationManager - 包裝常見 HTTP web 服務操作的類,通過AFHTTPRequestOperation 由 NSURLConnection 支持。
NSURLSession 組件 (iOS 7)
• AFURLSessionManager - 創建、管理基於 NSURLSessionConfiguration 對象的NSURLSession 對象的類,也可以管理 session 的數據、下載/上傳任務,實現 session 和其相關聯的任務的 delegate 方法。因爲 NSURLSession API 設計中奇怪的空缺,任何和NSURLSession 相關的代碼都可以用 AFURLSessionManager 改善。
• AFHTTPSessionManager - AFURLSessionManager 的子類,包裝常見的 HTTP web 服務操作,通過 AFURLSessionManager 由 NSURLSession 支持。


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


序列化
AFNetworking 2.0 新構架的突破之一是使用序列化來創建請求、解析響應。可以通過序列化的靈活設計將更多業務邏輯轉移到網絡層,並更容易定製之前內置的默認行爲。

- 符合這個協議的對象用於處理請求,它將請求參數轉換爲 query string 或是 entity body 的形式,並設置必要的 header。那些不喜歡 AFHTTPClient使用 query string 編碼參數的傢伙,你們一定喜歡這個。


- 符合這個協議的對象用於驗證、序列化響應及相關數據,轉換爲有用的形式,比如 JSON 對象、圖像、甚至基於 Mantle 的模型對象。相比沒完沒了地繼承 AFHTTPClient,現在 AFHTTPRequestOperation 有一個 responseSerializer 屬性,用於設置合適的 handler。同樣的,再也沒有沒用的受 NSURLProtocol 啓發的 request operation 類註冊,取而代之的還是很棒的 responseSerializer 屬性。謝天謝地。

安全性
感謝 Dustin Barker、Oliver Letterer、Kevin Harwood 等人做出的貢獻,AFNetworking 現在帶有內置的 SSL pinning 支持,這對於處理敏感信息的應用是十分重要的。
• AFSecurityPolicy - 評估服務器對安全連接針對指定的固定證書或公共密鑰的信任。tl;dr 將你的服務器證書添加到 app bundle,以幫助防止 中間人攻擊。
可達性
從 AFHTTPClient 解藕的另一個功能是網絡可達性。現在你可以直接使用它,或者使用AFHTTPRequestOperationManager / AFHTTPSessionManager 的屬性。
• AFNetworkReachabilityManager - 這個類監控當前網絡的可達性,提供回調 block 和 notificaiton,在可達性變化時調用。
實時性

AFEventSource - EventSource DOM API 的 Objective-C 實現。建立一個到某主機的持久 HTTP 連接,可以將事件傳輸到事件源並派發到聽衆。傳輸到事件源的消息的格式爲JSON Patch 文件,並被翻譯成 AFJSONPatchOperation 對象的數組。可以將這些 patch operation 應用到之前從服務器獲取的持久性數據集。 ~{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:在請求操作開始、停止加載時,自動開始、停止狀態欄上的網絡活動指示圖標。
• UIImageView+AFNetworking:增加了 imageResponseSerializer 屬性,可以輕鬆地讓遠程加載到 image view 上的圖像自動調整大小或應用濾鏡。比如,AFCoreImageSerializer可以在 response 的圖像顯示之前應用 Core Image filter。
• UIButton+AFNetworking (新):與 UIImageView+AFNetworking 類似,從遠程資源加載image 和 backgroundImage。
• UIActivityIndicatorView+AFNetworking (新):根據指定的請求操作和會話任務的狀態自動開始、停止 UIActivityIndicatorView。
• UIProgressView+AFNetworking (新):自動跟蹤某個請求或會話任務的上傳/下載進度。
• UIWebView+AFNetworking (新): 爲加載 URL 請求提供了更強大的API,支持進度回調和內容轉換。


於是終於要結束 AFNetworking 旋風之旅了。爲下一代應用設計的新功能,結合爲已有功能設計的全新架構,有很多東西值得興奮。
旗開得勝
將下列代碼加入 Podfile 就可以開始把玩 AFNetworking 2.0 了:
platform :ios, ‘7.0’pod “AFNetworking”, “2.0.0”

3.中文詳細解析
(點擊進入)
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中需要創建的UI
[objc] view plaincopyprint?
1.

@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. //添加下載任務
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];

//AFHTTPRequestOperationManager無參數的GET請求(成功)
[objc] view plaincopyprint?
1. - (void)GETTask1{//下載成功
2.
3. NSString *url = Musicurl;
4.
5. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
6.
7. manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不對數據解析
8.
9. //無參數的GET請求下載parameters:nil,也可以帶參數
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. //創建下載文件
31. if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
32.
33. //會自動將數據寫入文件
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. //設置下載的輸出流,而此輸出流寫入文件,這裏可以計算傳輸文件的大小
48. operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];
49.
50. __weak ViewController *weakSelf = self;
51.
52. //監聽的下載的進度
53. /*
54. *
55. * bytesRead 每次傳輸的數據包大小
56. * totalBytesRead 已下載的數據大小
57. * totalBytesExpectedToRead 總大小
58. *
59. */
60.
61. //調用Block監聽下載傳輸情況
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. }

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

[objc] view plaincopyprint?
1. - (void)POSTTask1{//發送微博成功
2.
3. NSMutableDictionary *params = [NSMutableDictionary dictionary];
4. [params setValue:@”正在發微博” forKey:@”status”];//發送微博的類容
5. [params setValue:@”xxxxxx” forKey:@”access_token”];//XXXXX自己註冊新浪微博開發賬號得到的令牌
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(@”發送成功:%@”,responseObject);
15.
16. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
17.
18. NSLog(@”網絡請求失敗:%@”,error);
19.
20. }];
21.
22. }

//AFHTTPRequestOperationManager複雜的POST請求——–Multi-Part(成功)

[objc] view plaincopyprint?
1. - (void)POSTTask2{
2.
3. //file://本地文件傳輸協議,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 formData) {//multipart/form-data編碼方式
28.
29. //方式二和三調用的方法,給的是URL
30. [formData appendPartWithFileURL:urlfile name:@”pic” error:nil];//name:@”pic”新浪微博要求的名字,去閱讀新浪的API文檔
31.
32. //方式三調用的方法,給的是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. //監聽進度
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. }

//AFHTTPRequestOperation(構建request,使用setCompletionBlockWithSuccess)(成功)
[objc] view plaincopyprint?
1. - (void)SimpleGETTaskOperation{//使用AFHTTPRequestOperation,不帶參數,無需指定請求的類型
2.
3. NSURL *URL = [NSURL URLWithString:Pictureurl];
4.
5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
6.
7. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
8.
9. // 進行操作的配置,設置解析序列化方式
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. }

//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 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. }

//創建一個下載任務———downloadTaskWithRequest(成功)
[objc] view plaincopyprint?
1. - (void)DownloadTask{//下載成功
2.
3. // 定義一個progress指針
4. NSProgress *progress = nil;
5.
6. // 創建一個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. // 開始下載任務
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. // 根據網址信息拼接成一個完整的文件存儲路徑並返回給block
26. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
27.
28. //———-可與寫入沙盒中————-
29.
30.
31. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
32. {
33. // 結束後移除掉這個progress
34. [progress removeObserver:self
35. forKeyPath:@”fractionCompleted”
36. context:NULL];
37. }];
38.
39. // 設置這個progress的唯一標示符
40. [progress setUserInfoObject:@”someThing” forKey:@”Y.X.”];
41.
42. [downloadTask resume];
43.
44. // 給這個progress添加監聽任務
45. [progress addObserver:self
46. forKeyPath:@”fractionCompleted”
47. options:NSKeyValueObservingOptionNew
48. context:NULL];
49. }
50. //監聽進度的方法(沒調用)
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. // 打印這個唯一標示符
58. NSLog(@”%@”, progress.userInfo);
59. }
60. }

//AFURLSessionManager下載隊列,且能在後臺下載,關閉了應用後還繼續下載(成功)
[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管理器中的下載任務
10. NSArray *downloadTasks = [SessionManage downloadTasks];
11.
12. // 如果有下載任務
13. if (downloadTasks.count)
14. {
15. NSLog(@”downloadTasks: %@”, downloadTasks);
16.
17. // 繼續全部的下載鏈接
18. for (NSURLSessionDownloadTask *downloadTask in downloadTasks)
19. {
20. [downloadTask resume];
21. }
22. }
23. }
24.
25. //點擊按鈕添加下載任務
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管理器添加一個下載任務
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. // 打印下載的標示
53. NSLog(@”%d”, downloadTask.taskIdentifier);
54. }

//創建一個數據任務(成功)
[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. //創建一個數據任務
12. NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
13. if (error) {
14. NSLog(@”Error: %@”, error);
15. } else {
16. //能將Json數據打印出來
17. NSLog(@”***** response = %@ \n************** responseObject = %@”, response, responseObject);
18. }
19. }];
20. [dataTask resume];
21.
22. }

//創建一個上傳的任務(尚未成功)
[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. }

//創建一個複雜的請求(尚未成功)
[objc] view plaincopyprint?
1. - (void)GreatComplexTask{
2.
3. NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@”POST” URLString:@”http://example.com/upload” parameters:nil constructingBodyWithBlock:^(id 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. }

發佈了26 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章