AFNetworking粗解(解析)

111180.png

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

AFNetworking翻譯注釋
Architecture(結構)
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 將通用的與服務器應用交互的操作封裝了起來,包括了請求的創建,回復的序列化,網絡指示器的監測,安全性,當然還有請求操作的管理。

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<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 創建了一個管理一個NSURLSession的對象,基于一個指定的NSURLSessionConfiguration對象,它與以下的這些協議融合在一起(<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>,<NSURLSessionDelegate>)。
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<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(創建一個數據任務)
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-urlencodedfoo=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<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.官網文檔外加點中文注釋

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

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 新構架的突破之一是使用序列化來創建請求、解析響應。可以通過序列化的靈活設計將更多業務邏輯轉移到網絡層,并更容易定制之前內置的默認行為。

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

<AFURLResponseSerializer> - 符合這個協議的對象用于驗證、序列化響應及相關數據,轉換為有用的形式,比如 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.  <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. //添加下載任務 
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];        //添加下載任務    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無參數的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. } 
- (void)GETTask1{//下載成功        NSString *url = Musicurl;        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];        manager.responseSerializer = [AFHTTPResponseSerializer serializer];//不對數據解析        //無參數的GET請求下載parameters:nil,也可以帶參數    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        //創建下載文件    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {                //會自動將數據寫入文件        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];            }        //加載進度視圖    [_activitView setAnimatingWithStateOfOperation:operation];        //使用AF封裝好的類目UIProgressView+AFNetworking.h    if (operation != nil) {        //下載進度        [_progressView setProgressWithDownloadProgressOfOperation:operation animated:YES];    }        //設置下載的輸出流,而此輸出流寫入文件,這里可以計算傳輸文件的大小    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];        __weak ViewController *weakSelf = self;        //監聽的下載的進度    /*     *     * bytesRead                每次傳輸的數據包大小     * totalBytesRead           已下載的數據大小     * totalBytesExpectedToRead 總大小     *     */        //調用Block監聽下載傳輸情況    [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{//發送微博成功 
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. } 
- (void)POSTTask1{//發送微博成功    NSMutableDictionary *params = [NSMutableDictionary dictionary];    [params setValue:@"正在發微博" forKey:@"status"];//發送微博的類容    [params setValue:@"xxxxxx" forKey:@"access_token"];//XXXXX自己注冊新浪微博開發賬號得到的令牌        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(@"發送成功:%@",responseObject);            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                NSLog(@"網絡請求失敗:%@",error);            }];}

//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<AFMultipartFormData> 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. } 
- (void)POSTTask2{      
  //file://本地文件傳輸協議,
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編碼方式               
 //方式二和三調用的方法,給的是URL      
  [formData appendPartWithFileURL:urlfile name:@"pic" error:nil];
//name:@"pic"新浪微博要求的名字,去閱讀新浪的API文檔             
   //方式三調用的方法,給的是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);    }];        
//監聽進度  
  [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {                
CGFloat progress = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite;        
NSLog(@"進度:%.1f",progress);            }];  
 }

//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. } 
- (void)SimpleGETTaskOperation{
//使用AFHTTPRequestOperation,不帶參數,無需指定請求的類型       
 NSURL *URL = [NSURL URLWithString:Pictureurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];     
   AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];       
 // 進行操作的配置,設置解析序列化方式      
  //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];
}

//創建一個下載任務---------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. } 
- (void)DownloadTask{
//下載成功       
 // 定義一個progress指針    
NSProgress *progress = nil;        
// 創建一個URL鏈接    
NSURL *url = [NSURL URLWithString:Pictureurl];        
// 初始化一個請求    
NSURLRequest *request = [NSURLRequest requestWithURL:url];       
 // 獲取一個Session管理器    
AFHTTPSessionManager *session = [AFHTTPSessionManager manager];        
// 開始下載任務    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/                                                                                                    // 根據網址信息拼接成一個完整的文件存儲路徑并返回給block                                                  
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];                                                                                                   
 //----------可與寫入沙盒中-------------                                                                                                                                                  } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)                                              {                                                  
// 結束后移除掉這個progress                                                  
[progress removeObserver:self                                                                forKeyPath:@"fractionCompleted"         context:NULL];                                 
             }];        
// 設置這個progress的唯一標示符   
 [progress setUserInfoObject:@"someThing" forKey:@"Y.X."];        
[downloadTask resume];      
  // 給這個progress添加監聽任務   
 [progress addObserver:self               forKeyPath:@"fractionCompleted"                  options:NSKeyValueObservingOptionNew                  context:NULL];}
//監聽進度的方法(沒調用)
- (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);                
// 打印這個唯一標示符        
NSLog(@"%@", progress.userInfo);   
 }}

//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. } 
- (void)DownloadTaskbackaAndqueue{       
 // 配置后臺下載會話配置    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"downloads"];        
// 初始化SessionManager管理器    
SessionManage = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        // 獲取添加到該SessionManager管理器中的下載任務    
NSArray *downloadTasks = [SessionManage downloadTasks];       
 // 如果有下載任務  
  if (downloadTasks.count)    {       
 NSLog(@"downloadTasks: %@", downloadTasks);                
// 繼續全部的下載鏈接       
 for (NSURLSessionDownloadTask *downloadTask in downloadTasks)  {        
    [downloadTask resume];    
    }  
  }}

//點擊按鈕添加下載任務

- (void)addDownloadTask:(id)sender{    
// 組織URL   
 NSURL *URL = [NSURL URLWithString:imagurl];        
// 組織請求    
NSURLRequest *request = [NSURLRequest requestWithURL:URL];        
// 給SessionManager管理器添加一個下載任務    
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];        
// 打印下載的標示    
NSLog(@"%d", downloadTask.taskIdentifier);
}

//創建一個數據任務(成功)

[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. } 
- (void)GreatDataTask{
//下載成功    
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];       
 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];        
NSURL *URL = [NSURL URLWithString:Jsonurl];       
 NSURLRequest *request = [NSURLRequest requestWithURL:URL];      
  //創建一個數據任務   
 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {        
if (error) {           
 NSLog(@"Error: %@", error);       
 } else {            
//能將Json數據打印出來            
NSLog(@"*************** response = %@ \n************** responseObject = %@", response, responseObject);       
 }   
 }];  
  [dataTask resume];   
 }

//創建一個上傳的任務(尚未成功)

[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];
}

//創建一個復雜的請求(尚未成功)

[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. }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內容

  • 在蘋果徹底棄用NSURLConnection之后自己總結的一個網上的內容,加上自己寫的小Demo,很多都是借鑒網絡...
    付寒宇閱讀 4,304評論 2 13
  • 二、 詳細介紹 1. AFNetworking 這是 AFNetworking 的主要部分,包括 6 個功能部分共...
    隨風飄蕩的小逗逼閱讀 4,473評論 0 2
  • AFN什么是AFN全稱是AFNetworking,是對NSURLConnection、NSURLSession的一...
    醉葉惜秋閱讀 1,233評論 0 0
  • 同步請求和異步請求- 同步請求:阻塞式請求,會導致用戶體驗的中斷- 異步請求:非阻塞式請求,不中斷用戶體驗,百度地...
    WangDavid閱讀 610評論 0 0
  • 今天有個小姑娘送了我一個娃娃,我很開心這是一種溫暖的感覺 其實我們并...
    聽誰在唱閱讀 176評論 0 0