afn原理

轉載http://www.th7.cn/Program/IOS/201503/405717.shtmlhtml

 

1    類庫功能簡介

1.1  AFNetworking的大致思路

1.1.1 NSURLConnection + NSOperation daozhe

NSURLConnection 是 Foundation URL加載系統的基石。一個 NSURLConnection 異步地加載一個 NSURLRequest 對象,調用delegate的 NSURLResponse / NSHTTPURLResponse 方法,其 NSData 被髮送到服務器或從服務器讀取;delegate還可用來處理 NSURLAuthenticationChallenge、重定向響應、或是決定 NSCachedURLResponse 如何存儲在共享的 NSURLCache上。git

NSOperation 是抽象類,模擬單個計算單元,有狀態、優先級、依賴等功能,能夠取消。github

AFNetworking的第一個重大突破就是將二者結合。AFURLConnectionOperation 做爲 NSOperation 的子類,遵循NSURLConnectionDelegate 的方法,能夠從頭至尾監視請求的狀態,並儲存請求、響應、響應數據等中間狀態。web

1.1.2 Blocks

iOS 4 引入的 block和 GrandCentral Dispatch從根本上改善了應用程序的開發過程。相比於在應用中用 delegate亂七八糟地實現邏輯,開發者們能夠用block將相關的功能放在一塊兒。GCD可以輕易來回調度工做,不用面對亂七八糟的線程、調用和操做隊列。json

更重要的是,對於每一個request operation,能夠經過 block自定義 NSURLConnectionDelegate 的方法(好比,經過setWillSendRequestForAuthenticationChallengeBlock: 能夠覆蓋默認的connection:willSendRequestForAuthenticationChallenge: 方法)。數組

如今,咱們能夠建立 AFURLConnectionOperation 並把它安排進 NSOperationQueue,經過設置 NSOperation 的新屬性completionBlock,指定操做完成時如何處理response和response data(或是請求過程當中遇到的錯誤)。promise

1.1.3 序列化 &驗證

更深刻一些,requestoperation操做也能夠負責驗證HTTP狀態碼和服務器響應的內容類型,好比,對於application/json MIME類型的響應,能夠將 NSData序列化爲JSON對象。緩存

從服務器加載 JSON、XML、property list或者圖像能夠抽象並類比成潛在的文件加載操做,這樣開發者能夠將這個過程想象成一個promise而不是異步網絡鏈接。安全

 

1.2     AFN 1.0版本

1.2.1  AFN1.0架構設計原理

AFN 的基礎部分是 AFURLConnectionOperation,一個 NSOperation subclass,實現了 基於NSURLConnection 相關的delegate+blocks,網絡部分是由 NSURLConnection 完成,而後利用 NSOperation 的 state (isReady→isExecuting→isFinished) 變化來進行網絡控制。網絡請求是在一個指定的線程(networkRequestThread)完成。性能優化

AFURLConnectionOperation是一個很純粹的網絡請求 operation,能夠對他進行start/cancel/pause/resume 操做,能夠獲取對應的 NSURLRequest 和 NSURLResponse 數據。支持 NSInputStream/NSOutputStream,提供了 uploadPress 和downloadProgress 以方便其餘使用。

AFHTTPRequestOperation是 AFURLConnectionOperation 的子類,針對 HTTP+HTTPS 協議作了一層封裝,好比statusCode、Content-Type 等,添加了請求成功和失敗的回調 block,提供了addAcceptableContentTypes: 以方便上層使用。

1.2.2  各個類功能說明

Ø  AFURLConnectionOperation和它的子類繼承NSOperation的,容許請求被取消,暫停/恢復和由NSOperationQueue進行管理。

Ø  AFURLConnectionOperation也可讓你輕鬆得完成上傳和下載,處理驗證,監控上傳和下載進度,控制的緩存。

Ø  AFHTTPRequestOperation和它得子類能夠基於http狀態和 內容列下來區分是否成功請求了。

Ø  AFNetworking能夠將遠程媒體數據類型(NSData)轉化爲可用的格式,好比如JSON,XML,圖像和plist。

Ø  AFHTTPClient提供了一個方便的網絡交互接口,包括默認頭,身份驗證,是否鏈接到網絡,批量處理操做,查詢字符串參數序列化,已經多種表單請求的UIImageView+ AFNetworking增長了一個方便的方法來異步加載圖像。

 

1.3     AFN 2.0版本

1.3.1 動機

·      兼容NSURLSession - NSURLSession 是 iOS 7 新引入的用於替代 NSURLConnection 的類。NSURLConnection 並無被棄用,從此一段時間應該也不會,可是 NSURLSession 是 Foundation中網絡的將來,而且是一個美好的將來,由於它改進了以前的不少缺點。(參考WWDC 2013 Session 705 「What’s New in Foundation Networking」,一個很好的概述)。起初有人推測,NSURLSession 的出現將使AFNetworking再也不有用。但實際上,雖然它們有一些重疊,AFNetworking仍是能夠提供更高層次的抽象。AFNetworking2.0不只作到了這一點,還藉助並擴展 NSURLSession來鋪平道路上的坑窪,並最大程度擴展了它的實用性。

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

 

1.3.2 主要組件

1.3.2.1NSURLConnection 組件 (iOS 6 & 7)

  • AFURLConnectionOperation - NSOperation 的子類,負責管理 NSURLConnection 而且實現其 delegate 方法。
  • AFHTTPRequestOperation - AFURLConnectionOperation 的子類,用於生成 HTTP 請求,能夠區別可接受的和不可接受的狀態碼及內容類型。2.0 版本中的最大區別是,你能夠直接使用這個類,而不用繼承它,緣由能夠在「序列化」一節中找到。
  • AFHTTPRequestOperationManager - 包裝常見 HTTP web 服務操做的類,經過 AFHTTPRequestOperation 由NSURLConnection 支持。

1.3.2.2NSURLSession 組件 (iOS 7)

  • AFURLSessionManager - 建立、管理基於 NSURLSessionConfiguration 對象的 NSURLSession 對象的類,也能夠管理 session 的數據、下載/上傳任務,實現 session 和其相關聯的任務的 delegate 方法。由於 NSURLSession API 設計中奇怪的空缺,任何和 NSURLSession 相關的代碼均可以用 AFURLSessionManager 改善
  • AFHTTPSessionManager - AFURLSessionManager 的子類,包裝常見的 HTTP web 服務操做,經過AFURLSessionManager 由 NSURLSession 支持。

1.3.3 綜述

總的來講:爲了支持新的 NSURLSession API 以及舊的未棄用且還有用的NSURLConnection,AFNetworking 2.0 的核心組件分紅了 request operation 和 session 任務。AFHTTPRequestOperationManager 和 AFHTTPSessionManager 提供相似的功能,在須要的時候(好比在 iOS 6 和 7 之間轉換),它們的接口能夠相對容易的互換。

1.3.4  功能特性

1.3.4.1             序列化

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

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

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

1.3.4.2             安全性

    AFNetworking如今帶有內置的 SSL pinning 支持,這對於處理敏感信息的應用是十分重要的。

  • AFSecurityPolicy - 評估服務器對安全鏈接針對指定的固定證書或公共密鑰的信任。將你的服務器證書添加到 app bundle,以幫助防止 中間人攻擊。

1.3.4.3             可達性

從 AFHTTPClient 解藕的另外一個功能是網絡可達性。如今你能夠直接使用它,或者使用 AFHTTPRequestOperationManager /AFHTTPSessionManager 的屬性。

l   AFNetworkReachabilityManager-這個類監控當前網絡的可達性,提供回調block和notificaiton,在可達性變化時調用。

1.3.4.4 實時性

 

l   AFEventSource - EventSourceDOM API 的 Objective-C實現。創建一個到某主機的持久HTTP鏈接,能夠將事件傳輸到事件源並派發到聽衆。傳輸到事件源的消息的格式爲 JSON Patch 文件,並被翻譯成AFJSONPatchOperation 對象的數組。能夠將這些patch operation 應用到以前從服務器獲取的持久性數據集。

 

 

NSURL *URL = [NSURLURLWithString:@"http://example.com"]; AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL]; 
[manager GET:@"/resources"parameters:nilsuccess:^(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];

1.3.4.5 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, 支持進度回調和內容轉換。

 

 

2    AFURLConnectionOperation類

 

@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate,NSURLConnectionDataDelegate, NSSecureCoding,NSCopying>

2.1     成員屬性

2.1.1  NSRunLoopCommonModes集合屬性

///-------------------------------

/// @name Accessing Run Loop Modes

///-------------------------------

 

/**

 The run loop modesin which the operation will run on the network thread. By default, this is asingle-member set containing `NSRunLoopCommonModes`.

 */

@property (nonatomic,strong)NSSet *runLoopModes;

2.1.2  NSURLRequest請求對象屬性

///-----------------------------------------

/// @name Getting URL Connection Information

///-----------------------------------------

 

/**

 The request usedby the operation's connection.

 */

@property (readonly,nonatomic,strong)NSURLRequest *request;

2.1.3  NSURLResponse響應對象屬性

/**

 The last responsereceived by the operation's connection.

 */

@property (readonly,nonatomic,strong)NSURLResponse*response;

2.1.4  請求生命週期過程當中產生的錯誤信息

/**

 The error, if any,that occurred in the lifecycle of the request.

 */

@property (readonly,nonatomic,strong)NSError *error;

 

///----------------------------

/// @name Getting Response Data

///----------------------------

2.1.5  響應數據屬性

/**

 The data receivedduring the request.

 */

@property (readonly,nonatomic,strong)NSData *responseData;

2.1.6  響應數據字符串

/**

 The stringrepresentation of the response data.

 */

@property (readonly,nonatomic,copy)NSString *responseString;

2.1.7  已編碼的響應數據字符串

/**

 The stringencoding of the response.

 

 If the responsedoes not specify a valid string encoding, `responseStringEncoding` will return`NSUTF8StringEncoding`.

 */

@property (readonly,nonatomic,assign)NSStringEncodingresponseStringEncoding;

2.1.8  是否使用存儲的共享憑證

///-------------------------------

/// @name Managing URL Credentials

///-------------------------------

 

/**

 Whether the URLconnection should consult the credential storage for authenticating theconnection. `YES` by default.

 

 This is the valuethat is returned in the `NSURLConnectionDelegate` method`-connectionShouldUseCredentialStorage:`.

 */

@property (nonatomic,assign)BOOL shouldUseCredentialStorage;

2.1.9  NSURLCredential憑證

/**

 The credentialused for authentication challenges in`-connection:didReceiveAuthenticationChallenge:`.

 

 This will beoverridden by any shared credentials that exist for the username or password ofthe request URL, if present.

 */

@property (nonatomic,strong)NSURLCredential*credential;

2.1.10             AFSecurityPolicy安全策略屬性

///-------------------------------

/// @name Managing Security Policy

///-------------------------------

 

/**

 The securitypolicy used to evaluate server trust for secure connections.

 */

@property (nonatomic,strong)AFSecurityPolicy*securityPolicy;

2.1.11             待發送數據的NSInputStream對象屬性

///------------------------

/// @name Accessing Streams

///------------------------

 

/**

 The input streamused to read data to be sent during the request.

 

 This property actsas a proxy to the `HTTPBodyStream` property of `request`.

 */

@property (nonatomic,strong)NSInputStream*inputStream;

2.1.12             接收數據的NSOutputStream對象屬性

/**

 The output streamthat is used to write data received until the request is finished.

 

By default, datais accumulated into a buffer that is stored into `responseData` upon completionof the request, with the intermediary `outputStream` property set to `nil`.When `outputStream` is set, the data will not be accumulated into an internalbuffer, and as a result, the `responseData` property of the completed requestwill be `nil`. The output stream will be scheduled in the network threadrunloop upon being set.

 */

@property (nonatomic,strong)NSOutputStream*outputStream;

2.1.13             請求完成後的處理隊列屬性

///---------------------------------

/// @name Managing Callback Queues

///---------------------------------

 

/**

 The dispatch queuefor `completionBlock`. If `NULL` (default), the main queue is used.

 */

@property (nonatomic,strong)dispatch_queue_tcompletionQueue;

2.1.14             請求完成後的處理Group屬性

/**

 The dispatch groupfor `completionBlock`. If `NULL` (default), a private dispatch group is used.

 */

@property (nonatomic,strong)dispatch_group_tcompletionGroup;

2.1.15             UserInfo字典屬性

///---------------------------------------------

/// @name Managing Request Operation Information

///---------------------------------------------

 

/**

 The user infodictionary for the receiver.

 */

@property (nonatomic,strong)NSDictionary *userInfo;

2.2     成員方法

2.2.1  初始化方法initWithRequest

///------------------------------------------------------

/// @name Initializing an AFURLConnectionOperation Object

///------------------------------------------------------

 

/**

 Initializes andreturns a newly allocated operation object with a url connection configuredwith the specified url request.

 

 This is thedesignated initializer.

 

 @param urlRequest Therequest object to be used by the operation connection.

 */

- (instancetype)initWithRequest:(NSURLRequest *)urlRequest;

2.2.2  暫停方法

///----------------------------------

/// @name Pausing / Resuming Requests

///----------------------------------

 

/**

 Pauses theexecution of the request operation.

 

A paused operationreturns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, itwill remain in an `NSOperationQueue` until it is either cancelled or resumed.Pausing a finished, cancelled, or paused operation has no effect.

 */

- (void)pause;

2.2.3  是否已暫停方法

/**

 Whether therequest operation is currently paused.

 

 @return `YES` if theoperation is currently paused, otherwise `NO`.

 */

- (BOOL)isPaused;

2.2.4  恢復請求方法

/**

 Resumes theexecution of the paused request operation.

 

Pause/Resumebehavior varies depending on the underlying implementation for the operationclass. In its base implementation, resuming a paused requests restarts theoriginal request. However, since HTTP defines a specification for how torequest a specific content range, `AFHTTPRequestOperation` will resumedownloading the request from where it left off, instead of restarting theoriginal request.

 */

- (void)resume;

2.2.5  設置是否能夠在後臺執行的方法

///----------------------------------------------

/// @name Configuring Backgrounding Task Behavior

///----------------------------------------------

 

/**

 Specifies that theoperation should continue execution after the app has entered the background,and the expiration handler for that background task.

 

 @paramhandler Ahandler to be called shortly before the application’s remaining background timereaches 0. The handler is wrapped in a block that cancels the operation, andcleans up and marks the end of execution, unlike the `handler` parameter in`UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects thisto be done in the handler itself. The handler is called synchronously on themain thread, thus blocking the application’s suspension momentarily while theapplication is notified.

  */

#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) &&!defined(AF_APP_EXTENSIONS)

- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;

#endif

2.2.6  設置上傳進度跟蹤block

///---------------------------------

/// @name Setting Progress Callbacks

///---------------------------------

 

/**

 Sets a callback tobe called when an undetermined number of bytes have been uploaded to theserver.

 

 @paramblock A blockobject to be called when an undetermined number of bytes have been uploaded tothe server. This block has no return value and takes three arguments: thenumber of bytes written since the last time the upload progress block wascalled, the total bytes written, and the total bytes expected to be writtenduring the request, as initially determined by the length of the HTTP body.This block may be called multiple times, and will execute on the main thread.

 */

- (void)setUploadProgressBlock:(void (^)(NSUIntegerbytesWritten,longlongtotalBytesWritten,longlong totalBytesExpectedToWrite))block;

2.2.7  設置下載進度跟蹤block

/**

 Sets a callback tobe called when an undetermined number of bytes have been downloaded from theserver.

 

 @paramblock A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes three arguments: thenumber of bytes read since the last time the download progress block wascalled, the total bytes read, and the total bytes expected to be read duringthe request, as initially determined by the expected content size of the`NSHTTPURLResponse` object. This block may be called multiple times, and willexecute on the main thread.

 */

- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead,longlongtotalBytesRead,longlongtotalBytesExpectedToRead))block;

2.2.8  發送驗證請求前執行的block

///-------------------------------------------------

/// @name Setting NSURLConnection Delegate Callbacks

///-------------------------------------------------

 

/**

Sets a block to beexecuted when the connection will authenticate a challenge in order to downloadits request, as handled by the `NSURLConnectionDelegate` method`connection:willSendRequestForAuthenticationChallenge:`.

 

 @paramblock A blockobject to be executed when the connection will authenticate a challenge inorder to download its request. The block has no return type and takes twoarguments: the URL connection object, and the challenge that must beauthenticated. This block must invoke one of the challenge-responder methods(NSURLAuthenticationChallengeSender protocol).

 

 If`allowsInvalidSSLCertificate` is set to YES,`connection:willSendRequestForAuthenticationChallenge:` will attempt to havethe challenge sender use credentials with invalid SSL certificates.

 */

- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection*connection,NSURLAuthenticationChallenge *challenge))block;

2.2.9  設置URL重定向時執行的block

/**

Sets a block to beexecuted when the server redirects the request from one URL to another URL, orwhen the request URL changed by the `NSURLProtocol` subclass handling therequest in order to standardize its format, as handled by the`NSURLConnectionDataDelegate` method`connection:willSendRequest:redirectResponse:`.

 

 @paramblock A blockobject to be executed when the request URL was changed. The block returns an`NSURLRequest` object, the URL request to redirect, and takes three arguments:the URL connection object, the the proposed redirected request, and the URLresponse that caused the redirect.

 */

- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection*connection,NSURLRequest *request,NSURLResponse*redirectResponse))block;

 

2.2.10             設置緩存響應前執行的block

/**

 Sets a block to beexecuted to modify the response a connection will cache, if any, as handled bythe `NSURLConnectionDelegate` method `connection:willCacheResponse:`.

 

 @paramblock A blockobject to be executed to determine what response a connection will cache, ifany. The block returns an `NSCachedURLResponse` object, the cached response tostore in memory or `nil` to prevent the response from being cached, and takestwo arguments: the URL connection object, and the cached response provided forthe request.

 */

- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection*connection,NSCachedURLResponse *cachedResponse))block;

2.2.11             批量處理方法

///

 

/**

 

 */

+ (NSArray *)batchOfRequestOperations:(NSArray *)operations

                       progressBlock:(void (^)(NSUIntegernumberOfFinishedOperations,NSUIntegertotalNumberOfOperations))progressBlock

                     completionBlock:(void (^)(NSArray*operations))completionBlock;

 

3    AFHTTPRequestOperation類

3.1     成員屬性

3.1.1  最後接收到的響應對象

///------------------------------------------------

/// @name Getting HTTP URL Connection Information

///------------------------------------------------

 

/**

 The last HTTPresponse received by the operation's connection.

 */

@property (readonly,nonatomic,strong)NSHTTPURLResponse *response;

3.1.2  AFHTTPResponseSerializer響應序列化器對象

/**

Responses sentfrom the server in data tasks created with `dataTaskWithRequest:success:failure:`and run using the `GET` / `POST` / et al. convenience methods are automaticallyvalidated and serialized by the response serializer. By default, this propertyis set to an AFHTTPResponse serializer, which uses the raw data as its responseobject. The serializer validates the status code to be in the `2XX` range,denoting success. If the response serializer generates an error in`-responseObjectForResponse:data:error:`, the `failure` callback of the sessiontask or request operation will be executed; otherwise, the `success` callbackwill be executed.

 

 @warning`responseSerializer` must not be `nil`. Setting a response serializer willclear out any cached value

 */

@property (nonatomic,strong)AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

3.1.3  序列化處理後的響應數據對象

/**

An objectconstructed by the `responseSerializer` from the response and response data.Returns `nil` unless the operation `isFinished`, has a `response`, and has`responseData` with non-zero content length. If an error occurs during serialization,`nil` will be returned, and the `error` property will be populated with theserialization error.

 */

@property (readonly,nonatomic,strong)id responseObject;

 

3.2     成員方法

3.2.1  請求結束後執行的block

///-----------------------------------------------------------

/// @name Setting Completion Block Success / Failure Callbacks

///-----------------------------------------------------------

 

/**

Sets the`completionBlock` property with a block that executes either the specifiedsuccess or failure block, depending on the state of the request on completion.If `error` returns a value, which can be caused by an unacceptable status codeor content type, then `failure` is executed. Otherwise, `success` is executed.

 

 This method shouldbe overridden in subclasses in order to specify the response object passed intothe success block.

 

 @paramsuccess Theblock to be executed on the completion of a successful request. This block hasno return value and takes two arguments: the receiver operation and the objectconstructed from the response data of the request.

 @paramfailure Theblock to be executed on the completion of an unsuccessful request. This blockhas no return value and takes two arguments: the receiver operation and theerror that occurred during the request.

 */

- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation*operation,idresponseObject))success

                              failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

 

4    AFHTTPRequestOperationManager類

4.1     成員屬性

4.1.1  域名或者頂級目錄URL

/**

 The URL used tomonitor reachability, and construct requests from relative paths in methodslike `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al.convenience methods.

 */

@property (readonly,nonatomic,strong)NSURL *baseURL;

4.1.2  AFHTTPRequestSerializer請求序列化器

/**

Requests createdwith `requestWithMethod:URLString:parameters:` &`multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`are constructed with a set of default headers using a parameter serializationspecified by this property. By default, this is set to an instance of`AFHTTPRequestSerializer`, which serializes query string parameters for `GET`,`HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP messagebodies.

 

 @warning`requestSerializer` must not be `nil`.

 */

@property (nonatomic,strong)AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;

4.1.3  AFHTTPResponseSerializer響應序列化器

/**

Responses sentfrom the server in data tasks created with`dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / etal. convenience methods are automatically validated and serialized by theresponse serializer. By default, this property is set to a JSON serializer,which serializes data from responses with a `application/json` MIME type, andfalls back to the raw data object. The serializer validates the status code tobe in the `2XX` range, denoting success. If the response serializer generatesan error in `-responseObjectForResponse:data:error:`, the `failure` callback ofthe session task or request operation will be executed; otherwise, the`success` callback will be executed.

 

 @warning`responseSerializer` must not be `nil`.

 */

@property (nonatomic,strong)AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

4.1.4  操做隊列

/**

 The operationqueue on which request operations are scheduled and run.

 */

@property (nonatomic,strong)NSOperationQueue*operationQueue;

4.1.5  設置是否須要存儲憑證

///-------------------------------

/// @name Managing URL Credentials

///-------------------------------

 

/**

 Whether requestoperations should consult the credential storage for authenticating theconnection. `YES` by default.

 

 @see AFURLConnectionOperation-shouldUseCredentialStorage

 */

@property (nonatomic,assign)BOOLshouldUseCredentialStorage;

4.1.6  NSURLCredential憑證對象

/**

 The credentialused by request operations for authentication challenges.

 

 @seeAFURLConnectionOperation -credential

 */

@property (nonatomic,strong)NSURLCredential*credential;

4.1.7  AFSecurityPolicy安全策略對象

///-------------------------------

/// @name Managing Security Policy

///-------------------------------

 

/**

 The securitypolicy used by created request operations to evaluate server trust for secureconnections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unlessotherwise specified.

 */

@property (nonatomic,strong)AFSecurityPolicy*securityPolicy;

4.1.8  網絡監控對象

///------------------------------------

/// @name Managing Network Reachability

///------------------------------------

 

/**

 The networkreachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager`by default.

 */

@property (readwrite,nonatomic,strong)AFNetworkReachabilityManager*reachabilityManager;

4.1.9  請求完成處理隊列

///-------------------------------

/// @name Managing Callback Queues

///-------------------------------

 

/**

 The dispatch queuefor the `completionBlock` of request operations. If `NULL` (default), the mainqueue is used.

 */

@property (nonatomic,strong)dispatch_queue_tcompletionQueue;

4.1.10             請求完成處理Group

/**

 The dispatch groupfor the `completionBlock` of request operations. If `NULL` (default), a privatedispatch group is used.

 */

@property (nonatomic,strong)dispatch_group_tcompletionGroup;

 

///---------------------------------------------

/// @name Creating and Initializing HTTP Clients

///---------------------------------------------

 

4.2     成員方法

4.2.1  單例方法

/**

 Creates andreturns an `AFHTTPRequestOperationManager` object.

 */

+ (instancetype)manager;

4.2.2  初始化方法initWithBaseURL

/**

 Initializes an`AFHTTPRequestOperationManager` object with the specified base URL.

 

 This is thedesignated initializer.

 

 @param url The baseURL for the HTTP client.

 

 @return Thenewly-initialized HTTP client

 */

- (instancetype)initWithBaseURL:(NSURL *)url;

4.2.3  建立AFHTTPRequestOperation對象方法

///---------------------------------------

/// @name Managing HTTP Request Operations

///---------------------------------------

 

/**

 Creates an`AFHTTPRequestOperation`, and sets the response serializers to that of the HTTPclient.

 

 @param request Therequest object to be loaded asynchronously during execution of the operation.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the created requestoperation and the object created from the response data of request.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes two arguments:, thecreated request operation and the `NSError` object describing the network orparsing error that occurred.

 */

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest*)request

                                                   success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success

                                                   failure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure;

 

///---------------------------

/// @name Making HTTP Requests

///---------------------------

4.2.4  建立一個Get請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `GET` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)GET:(NSString *)URLString

                    parameters:(id)parameters

                       success:(void (^)(AFHTTPRequestOperation *operation,idresponseObject))success

                        failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.5  建立一個Head請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `HEAD` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes a single arguments: the requestoperation.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString

                     parameters:(id)parameters

                        success:(void (^)(AFHTTPRequestOperation*operation))success

                        failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.6  建立一個Post請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `POST` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)POST:(NSString *)URLString

                     parameters:(id)parameters

                         success:(void (^)(AFHTTPRequestOperation*operation,idresponseObject))success

                        failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.7  建立多個Post請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a multipart `POST` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @param block A blockthat takes a single argument and appends data to the HTTP body. The blockargument is an object adopting the `AFMultipartFormData` protocol.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)POST:(NSString *)URLString

                     parameters:(id)parameters

      constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block

                         success:(void (^)(AFHTTPRequestOperation*operation,idresponseObject))success

                        failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.8  建立一個Put請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `PUT` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)PUT:(NSString *)URLString

                    parameters:(id)parameters

                       success:(void (^)(AFHTTPRequestOperation *operation,idresponseObject))success

                       failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.9 建立一個Patch請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `PATCH` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString

                      parameters:(id)parameters

                         success:(void (^)(AFHTTPRequestOperation *operation,idresponseObject))success

                         failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

4.2.10             建立一個Delete請求的AFHTTPRequestOperation對象

/**

 Creates and runsan `AFHTTPRequestOperation` with a `DELETE` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.

 @paramfailure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.

 

 @see-HTTPRequestOperationWithRequest:success:failure:

 */

- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString

                       parameters:(id)parameters

                          success:(void (^)(AFHTTPRequestOperation *operation,idresponseObject))success

                          failure:(void (^)(AFHTTPRequestOperation*operation,NSError *error))failure;

 

 

 

5    NSURLSession

5.1    URL Session的基本概念

    NSURLSession是iOS7中新的網絡接口,它與我們熟悉的NSURLConnection是並列的。在程序在前臺時,NSURLSession與NSURLConnection能夠互爲替代工做。注意,若是用戶強制將程序關閉,NSURLSession會斷掉。

 

NSURLSession提供的功能:

1.經過URL將數據下載到內存

2.經過URL將數據下載到文件系統

3.將數據上傳到指定URL

4.在後臺完成上述功能

 

5.1.1 三種工做模式

默認會話模式(default):工做模式相似於原來的NSURLConnection,使用的是基於磁盤緩存的持久化策略,使用用戶keychain中保存的證書進行認證受權。

瞬時會話模式(ephemeral):該模式不使用磁盤保存任何數據。全部和會話相關的caches,證書,cookies等都被保存在RAM中,所以當程序使會話無效,這些緩存的數據就會被自動清空。

後臺會話模式(background):該模式在後臺完成上傳和下載,在建立Configuration對象的時候須要提供一個NSString類型的ID用於標識完成工做的後臺會話。

 

5.1.2 NSURLSession支持的三種任務

NSURLSession類支持三種類型的任務:加載數據,下載和上傳。

 

5.2     NSURLSession相關的類

NSURLConnection這個名字,實際上指的是一組構成Foundation框架中URL加載系統的相互關聯的組件:NSURLRequest,NSURLResponse,NSURLProtocol,NSURLCache,NSHTTPCookieStorage,NSURLCredentialStorage,以及和它同名的NSURLConnection。

在WWDC2013中,Apple的團隊對NSURLConnection進行了重構,並推出了NSURLSession做爲替代。

    NSURLSession也是一組相互依賴的類,它的大部分組件和NSURLConnection中的組件相同如NSURLRequest,NSURLCache等。而NSURLSession的不一樣之處在於,它將NSURLConnection替換爲NSURLSession和NSURLSessionConfiguration,以及3個NSURLSessionTask的子類:NSURLSessionDataTask, NSURLSessionUploadTask, 和NSURLSessionDownloadTask。

 

5.2.1 NSURLSessionConfiguration類

5.2.1.1 簡介

其中NSURLSessionConfiguration用於配置會話的屬性,能夠經過該類配置會話的工做模式:

[objc] view plaincopy

1.  + (NSURLSessionConfiguration *)defaultSessionConfiguration;  

2. + (NSURLSessionConfiguration *)ephemeralSessionConfiguration;  

3.  + (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier;  

 

在backgroundSessionConfiguration:方法中的identifier參數指定了會話的ID,用於標記後臺的session。

該類的其中兩個屬性:

[objc] view plaincopy

1.  /* allow request to route over cellular. */  

2. @property BOOL allowsCellularAccess;  

3.    

4. /* allows background tasks to be scheduled at the discretion of the system for optimal performance. */  

5. @property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(NA, 7_0);  

 

allowsCellularAccess 屬性指定是否容許使用蜂窩鏈接,discretionary屬性爲YES時表示當程序在後臺運做時由系統本身選擇最佳的網絡鏈接配置,該屬性能夠節省經過蜂窩鏈接的帶寬。在使用後臺傳輸數據的時候,建議使用discretionary屬性,而不是allowsCellularAccess屬性,由於它會把WiFi和電源可用性考慮在內。補充:這個標誌容許系統爲分配任務進行性能優化。這意味着只有當設備有足夠電量時,設備才經過Wifi進行數據傳輸。若是電量低,或者只僅有一個蜂窩鏈接,傳輸任務是不會運行的。後臺傳輸老是在discretionary模式下運行。

5.2.1.2 NSURLSessionConfiguration類屬性與方法

/*

 * Configurationoptions for an NSURLSession.  When asession is

 * created, a copyof the configuration object is made - you cannot

 * modify theconfiguration of a session after it has been created.

 *

 * The sharedsession uses the global singleton credential, cache

 * and cookiestorage objects.

 *

 * An ephemeralsession has no persistent disk storage for cookies,

 * cache orcredentials.

 *

 * A backgroundsession can be used to perform networking operations

 * on behalf of asuspended application, within certain constraints.

 */

NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0)

@interfaceNSURLSessionConfiguration :NSObject <NSCopying>

 

+ (NSURLSessionConfiguration *)defaultSessionConfiguration;

+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;

+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifierNS_AVAILABLE(10_10,8_0);

 

/* identifier for the background session configuration */

@property (readonly,copy)NSString *identifier;

 

/* default cache policy for requests */

@property NSURLRequestCachePolicy requestCachePolicy;

 

/* default timeout for requests.  This will cause a timeout if no data istransmitted for the given timeout value, and is reset whenever data istransmitted. */

@property NSTimeIntervaltimeoutIntervalForRequest;

 

/* default timeout for requests.  This will cause a timeout if a resource isnot able to be retrieved within a given timeout. */

@property NSTimeIntervaltimeoutIntervalForResource;

 

/* type of service for requests. */

@property NSURLRequestNetworkServiceType networkServiceType;

 

/* allow request to route over cellular. */

@property BOOLallowsCellularAccess;

 

/* allows background tasks to be scheduled at thediscretion of the system for optimal performance. */

@property (getter=isDiscretionary)BOOL discretionaryNS_AVAILABLE(10_10,7_0);

 

/* The identifier of the shared data container into whichfiles in background sessions should be downloaded.

 * App extensionswishing to use background sessions *must* set this property to a validcontainer identifier, or

 * the session willbe invalidated upon creation.

 */

@property (copy)NSString*sharedContainerIdentifierNS_AVAILABLE(10_10,8_0);

 

/*

 * Allows the appto be resumed or launched in the background when tasks in background sessionscomplete

 * or when auth isrequired. This only applies to configurations created with+backgroundSessionConfigurationWithIdentifier:

 * and the defaultvalue is YES.

 */

@property BOOLsessionSendsLaunchEvents NS_AVAILABLE(NA,7_0);

 

/* The proxy dictionary, as described by<CFNetwork/CFHTTPStream.h> */

@property (copy)NSDictionary*connectionProxyDictionary;

 

/* The minimum allowable versions of the TLS protocol,from <Security/SecureTransport.h> */

@property SSLProtocolTLSMinimumSupportedProtocol;

 

/* The maximum allowable versions of the TLS protocol,from <Security/SecureTransport.h> */

@property SSLProtocolTLSMaximumSupportedProtocol;

 

/* Allow the use of HTTP pipelining */

@property BOOLHTTPShouldUsePipelining;

 

/* Allow the session to set cookies on requests */

@property BOOLHTTPShouldSetCookies;

 

/* Policy for accepting cookies.  This overrides the policy otherwise specifiedby the cookie storage. */

@property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy;

 

/* Specifies additional headers which will be set onoutgoing requests.

   Note that theseheaders are added to the request only if not already present. */

@property (copy)NSDictionary*HTTPAdditionalHeaders;

 

/* The maximum number of simultanous persistentconnections per host */

@property NSIntegerHTTPMaximumConnectionsPerHost;

 

/* The cookie storage object to use, or nil to indicatethat no cookies should be handled */

@property (retain)NSHTTPCookieStorage *HTTPCookieStorage;

 

/* The credential storage object, or nil to indicate thatno credential storage is to be used */

@property (retain)NSURLCredentialStorage *URLCredentialStorage;

 

/* The URL resource cache, or nil to indicate that nocaching is to be performed */

@property (retain)NSURLCache *URLCache;

 

/* An optional array of Class objects which subclassNSURLProtocol. 

   The Class willbe sent +canInitWithRequest: when determining if

   an instance ofthe class can be used for a given URL scheme.

   You should notuse +[NSURLProtocol registerClass:], as that

   method willregister your class with the default session rather

   than with aninstance of NSURLSession.

   CustomNSURLProtocol subclasses are not available to background

   sessions.

 */

@property (copy)NSArray*protocolClasses;

 

@end

 

 

5.2.2 NSURLSession類

5.2.2.1 獲取NSURLSession類對象有幾種方式

獲取NSURLSession類對象有幾種方式:

[objc] view plaincopy

  1. /* 
  2.  * The shared session uses the currently set global NSURLCache, 
  3.  * NSHTTPCookieStorage and NSURLCredentialStorage objects. 
  4.  */  
  5. + (NSURLSession *)sharedSession;  
  6.   
  7. /* 
  8.  * Customization of NSURLSession occurs during creation of a new session. 
  9.  * If you only need to use the convenience routines with custom 
  10.  * configuration options it is not necessary to specify a delegate. 
  11.  * If you do specify a delegate, the delegate will be retained until after 
  12.  * the delegate has been sent the URLSession:didBecomeInvalidWithError: message. 
  13.  */  
  14. + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;  
  15. + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;  

 

第一種方式是使用靜態的sharedSession方法,該類使用共享的會話,該會話使用全局的Cache,Cookie和證書。

第二種方式是經過sessionWithConfiguration:方法建立對象,也就是建立對應配置的會話,與NSURLSessionConfiguration合做使用。

第三種方式是經過sessionWithConfiguration:delegate:delegateQueue方法建立對象,二三兩種方式能夠建立一個新會話並定製其會話類型。該方式中指定了session的委託和委託所處的隊列。當再也不須要鏈接時,能夠調用Session的invalidateAndCancel直接關閉,或者調用finishTasksAndInvalidate等待當前Task結束後關閉。這時Delegate會收到URLSession:didBecomeInvalidWithError:這個事件。Delegate收到這個事件以後會被解引用。

5.2.2.2 成員屬性與方法

NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0)

@interface NSURLSession : NSObject

 

/*

 * The sharedsession uses the currently set global NSURLCache,

 *NSHTTPCookieStorage and NSURLCredentialStorage objects.

 */

+ (NSURLSession *)sharedSession;

 

/*

 * Customization ofNSURLSession occurs during creation of a new session.

 * If you only needto use the convenience routines with custom

 * configurationoptions it is not necessary to specify a delegate.

 * If you dospecify a delegate, the delegate will be retained until after

 * the delegate hasbeen sent the URLSession:didBecomeInvalidWithError: message.

 */

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration*)configuration;

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration*)configurationdelegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;

 

@property (readonly,retain)NSOperationQueue*delegateQueue;

@property (readonly,retain)id <NSURLSessionDelegate> delegate;

@property (readonly,copy)NSURLSessionConfiguration *configuration;

 

/*

 * ThesessionDescription property is available for the developer to

 * provide adescriptive label for the session.

 */

@property (copy)NSString*sessionDescription;

 

/* -finishTasksAndInvalidate returns immediately andexisting tasks will be allowed

 * to run tocompletion.  New tasks may not becreated.  The session

 * will continue tomake delegate callbacks until URLSession:didBecomeInvalidWithError:

 * has been issued.

 *

 *-finishTasksAndInvalidate and -invalidateAndCancel do not

 * have any effecton the shared session singleton.

 */

- (void)finishTasksAndInvalidate;

 

/* -invalidateAndCancel acts as-finishTasksAndInvalidate, but issues

 * -cancel to alloutstanding tasks for this session.  Notetask

 * cancellation issubject to the state of the task, and some tasks may

 * have alreadyhave completed at the time they are sent -cancel.

 */

- (void)invalidateAndCancel;

 

- (void)resetWithCompletionHandler:(void (^)(void))completionHandler;   /* emptyall cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:.Invokes completionHandler() on the delegate queue if not nil. */

- (void)flushWithCompletionHandler:(void (^)(void))completionHandler;   /* flushstorage to disk and clear transient network caches.  Invokes completionHandler() on the delegatequeue if not nil. */

 

- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks,NSArray*uploadTasks,NSArray *downloadTasks))completionHandler; /* invokes completionHandler with outstanding data,upload and download tasks. */

 

/*

 * NSURLSessionTaskobjects are always created in a suspended state and

 * must be sent the-resume message before they will execute.

 */

 

/* Creates a data task with the given request.  The request may have a body stream. */

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;

 

/* Creates a data task to retrieve the contents of thegiven URL. */

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;

 

/* Creates an upload task with the given request.  The body of the request will be created fromthe file referenced by fileURL */

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;

 

/* Creates an upload task with the given request.  The body of the request is provided from thebodyData. */

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;

 

/* Creates an upload task with the given request.  The previously set body stream of the request(if any) is ignored and the URLSession:task:needNewBodyStream: delegate will becalled when the body payload is required. */

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest*)request;

 

/* Creates a download task with the given request. */

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;

 

/* Creates a download task to download the contents ofthe given URL. */

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;

 

/* Creates a download task with the resume data.  If the download cannot be successfully resumed,URLSession:task:didCompleteWithError: will be called. */

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;

 

@end

5.2.2.3 NSURLSession(NSURLSessionAsynchronousConvenience)

/*

 * NSURLSessionconvenience routines deliver results to

 * a completionhandler block.  These convenienceroutines

 * are notavailable to NSURLSessions that are configured

 * as backgroundsessions.

 *

 * Task objects arealways created in a suspended state and

 * must be sent the-resume message before they will execute.

 */

@interface NSURLSession(NSURLSessionAsynchronousConvenience)

/*

 * data taskconvenience methods.  These methodscreate tasks that

 * bypass thenormal delegate calls for response and data delivery,

 * and provide asimple cancelable asynchronous interface to receiving

 * data.  Errors will be returned in theNSURLErrorDomain,

 * see<Foundation/NSURLError.h>.  Thedelegate, if any, will still be

 * called forauthentication challenges.

 */

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest*)requestcompletionHandler:(void (^)(NSData *data, NSURLResponse *response,NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void(^)(NSData *data,NSURLResponse*response,NSError *error))completionHandlerNS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

 

/*

 * uploadconvenience method.

 */

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURLcompletionHandler:(void (^)(NSData *data, NSURLResponse*response, NSError*error))completionHandlerNS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyDatacompletionHandler:(void (^)(NSData *data,NSURLResponse *response, NSError*error))completionHandlerNS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

 

/*

 * download taskconvenience methods.  When a downloadsuccessfully

 * completes, theNSURL will point to a file that must be read or

 * copied duringthe invocation of the completion routine. The file

 * will be removedautomatically.

 */

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest*)requestcompletionHandler:(void (^)(NSURL *location, NSURLResponse *response,NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location,NSURLResponse*response,NSError*error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse*response, NSError*error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

 

@end

 

5.2.3 NSURLSessionTask類

5.2.3.1 簡介

   NSURLSessionTask是一個抽象子類,它有三個子類:NSURLSessionDataTask,NSURLSessionUploadTask和NSURLSessionDownloadTask。這三個類封裝了現代應用程序的三個基本網絡任務:獲取數據,好比JSON或XML,以及上傳和下載文件。

下面是其繼承關係:

有多種方法建立對應的任務對象:

5.2.3.2 NSURLSessionTask類屬性與方法

typedef NS_ENUM(NSInteger,NSURLSessionTaskState) {

   NSURLSessionTaskStateRunning = 0,                    /* The task is currently being serviced bythe session */

   NSURLSessionTaskStateSuspended = 1,

   NSURLSessionTaskStateCanceling = 2,                  /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError:message. */

   NSURLSessionTaskStateCompleted = 3,                  /* The task has completed and the session will receive no more delegatenotifications */

} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

 

/*

 * NSURLSessionTask- a cancelable object that refers to the lifetime

 * of processing agiven request.

 */

NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE,7_0)

@interface NSURLSessionTask: NSObject <NSCopying>

 

@property (readonly)NSUInteger taskIdentifier;             /* an identifier for this task, assigned byand unique to the owning session */

@property (readonly,copy)NSURLRequest*originalRequest;

@property (readonly,copy)NSURLRequest*currentRequest;   /* may differ from originalRequest due to http serverredirection */

@property (readonly,copy)NSURLResponse*response;    /* maybe nil if no response has been received */

 

/* Byte count properties may be zero if no body isexpected,

 * orNSURLSessionTransferSizeUnknown if it is not possible

 * to know how manybytes will be transferred.

 */

 

/* number of body bytes already received */

@property (readonly)int64_tcountOfBytesReceived;

 

/* number of body bytes already sent */

@property (readonly)int64_tcountOfBytesSent;

 

/* number of body bytes we expect to send, derived fromthe Content-Length of the HTTP request */

@property (readonly)int64_tcountOfBytesExpectedToSend;

 

/* number of byte bytes we expect to receive, usuallyderived from the Content-Length header of an HTTP response. */

@property (readonly)int64_tcountOfBytesExpectedToReceive;

 

/*

 * ThetaskDescription property is available for the developer to

 * provide adescriptive label for the task.

 */

@property (copy)NSString*taskDescription;

 

/* -cancel returns immediately, but marks a task as beingcanceled.

 * The task willsignal -URLSession:task:didCompleteWithError: with an

 * error value of {NSURLErrorDomain, NSURLErrorCancelled }. In some

 * cases, the taskmay signal other work before it acknowledges the

 *cancelation.  -cancel may be sent to atask that has been suspended.

 */

- (void)cancel;

 

/*

 * The currentstate of the task within the session.

 */

@property (readonly)NSURLSessionTaskState state;

 

/*

 * The error, ifany, delivered via -URLSession:task:didCompleteWithError:

 * This propertywill be nil in the event that no error occured.

 */

@property (readonly,copy)NSError *error;

 

/*

 * Suspending atask will prevent the NSURLSession from continuing to

 * load data.  There may still be delegate calls made onbehalf of

 * this task (forinstance, to report data received while suspending)

 * but no furthertransmissions will be made on behalf of the task

 * until -resume issent.  The timeout timer associated withthe task

 * will be disabledwhile a task is suspended. -suspend and -resume are

 * nestable.

 */

- (void)suspend;

- (void)resume;

 

/*

 * Sets a scalingfactor for the priority of the task. The scaling factor is a

 * value between0.0 and 1.0 (inclusive), where 0.0 is considered the lowest

 * priority and 1.0is considered the highest.

 *

 * The priority isa hint and not a hard requirement of task performance. The

 * priority of atask may be changed using this API at any time, but not all

 * protocolssupport this; in these cases, the last priority that took effect

 * will be used.

 *

 * If no priorityis specified, the task will operate with the default priority

 * as defined bythe constant NSURLSessionTaskPriorityDefault. Two additional

 * priority levelsare provided: NSURLSessionTaskPriorityLow and

 *NSURLSessionTaskPriorityHigh, but use is not restricted to these.

 */

@property float priority NS_AVAILABLE(10_10,8_0);

 

@end

 

5.2.3.3 NSURLSessionDataTask

經過request對象或url建立:

[objc] view plaincopy

1. /* Creates a data task with the given request.  The request may have a body stream. */  

2. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;  

3.    

4. /* Creates a data task to retrieve the contents of the given URL. */  

5.  - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;  

經過request對象或url建立,同時指定任務完成後經過completionHandler指定回調的代碼塊:

[objc] view plaincopy

1.  /* 

2.  * data task convenience methods.  These methods create tasks that 

3.   * bypass the normal delegate calls for response and data delivery, 

4.  * and provide a simple cancelable asynchronous interface to receiving 

5.   * data.  Errors will be returned in the NSURLErrorDomain,  

6.  * see <Foundation/NSURLError.h>.  The delegate, if any, will still be 

7.   * called for authentication challenges. 

8.  */  

9.  - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;  

10.- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;  

 

5.2.3.4 NSURLSessionUploadTask

經過request建立,在上傳時指定文件源或數據源。

[objc] view plaincopy

1. /* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */  

2. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;  

3.    

4. /* Creates an upload task with the given request.  The body of the request is provided from the bodyData. */  

5.  - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;  

6.   

7. /* Creates an upload task with the given request.  The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */  

8. - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;  

在建立upload task對象時,經過completionHandler指定任務完成後的回 調代碼塊:

[objc] view plaincopy

1.  /* 

2.  * upload convenience method. 

3.   */  

4. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;  

5.  - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;  

 

(3)NSURLSessionDownloadTask

[objc] view plaincopy

1.  /* Creates a download task with the given request. */  

2. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;  

3.    

4. /* Creates a download task to download the contents of the given URL. */  

5.  - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;  

6.   

7. /* Creates a download task with the resume data.  If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */  

8. - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;  

下載任務支持斷點續傳,第三種方式是經過以前已經下載的數據來建立下載任務。

一樣地能夠經過completionHandler指定任務完成後的回調代碼塊:

[objc] view plaincopy

1.  /* 

2.  * download task convenience methods.  When a download successfully 

3.   * completes, the NSURL will point to a file that must be read or 

4.  * copied during the invocation of the completion routine.  The file 

5.   * will be removed automatically. 

6.  */  

7.  - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;  

8. - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;  

9.  - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;  

 

5.2.4 NSURLSessionDelegate協議

 

NSURLSessionDelegate協議方法

typedef NS_ENUM(NSInteger,NSURLSessionResponseDisposition) {

   NSURLSessionResponseCancel = 0,                                /* Cancel the load, this is the same as -[task cancel] */

   NSURLSessionResponseAllow = 1,                                  /* Allow the load to continue */

   NSURLSessionResponseBecomeDownload = 2,                         /* Turn this request into a download */

} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE,7_0);

 

/*

 *NSURLSessionDelegate specifies the methods that a session delegate

 * may respondto.  There are both session specificmessages (for

 * example,connection based auth) as well as task based messages.

 */

 

/*

 * Messages relatedto the URL session as a whole

 */

@protocol NSURLSessionDelegate<NSObject>

@optional

 

/* The last message a session receives.  A session will only become

 * invalid becauseof a systemic error or when it has been

 * explicitlyinvalidated, in which case the error parameter will be nil.

 */

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError*)error;

 

/* If implemented, when a connection level authenticationchallenge

 * has occurred,this delegate will be given the opportunity to

 * provideauthentication credentials to the underlying

 * connection. Sometypes of authentication will apply to more than

 * one request on agiven connection to a server (SSL Server Trust

 *challenges).  If this delegate message isnot implemented, the

 * behavior will beto use the default handling, which may involve user

 * interaction.

 */

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge

                                            completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,NSURLCredential*credential))completionHandler;

 

/* If an application has received an

 *-application:handleEventsForBackgroundURLSession:completionHandler:

 * message, thesession delegate will receive this message to indicate

 * that all messagespreviously enqueued for this session have been

 * delivered.  At this time it is safe to invoke thepreviously stored

 * completionhandler, or to begin any internal updates that will

 * result ininvoking the completion handler.

 */

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession*)sessionNS_AVAILABLE_IOS(7_0);

 

@end

5.2.5  NSURLSessionTaskDelegate協議

/*

 * Messages relatedto the operation of a specific task.

 */

@protocolNSURLSessionTaskDelegate <NSURLSessionDelegate>

@optional

 

/* An HTTP request is attempting to perform a redirectionto a different

 * URL. You mustinvoke the completion routine to allow the

 * redirection,allow the redirection with a modified request, or

 * pass nil to thecompletionHandler to cause the body of the redirection

 * response to bedelivered as the payload of this request. The default

 * is to followredirections.

 *

 * For tasks inbackground sessions, redirections will always be followed and this method willnot be called.

 */

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

                    willPerformHTTPRedirection:(NSHTTPURLResponse *)response

                                    newRequest:(NSURLRequest *)request

                             completionHandler:(void (^)(NSURLRequest*))completionHandler;

 

/* The task has received a request specificauthentication challenge.

 * If this delegateis not implemented, the session specific authentication challenge

 * will *NOT* becalled and the behavior will be the same as using the default handling

 * disposition.

 */

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

                           didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge

                              completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,NSURLCredential*credential))completionHandler;

 

/* Sent if a task requires a new, unopened bodystream.  This may be

 * necessary whenauthentication has failed for any request that

 * involves a bodystream.

 */

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

                             needNewBodyStream:(void (^)(NSInputStream*bodyStream))completionHandler;

 

/* Sent periodically to notify the delegate of upload progress.  This

 * information isalso available as properties of the task.

 */

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

                               didSendBodyData:(int64_t)bytesSent

                                 totalBytesSent:(int64_t)totalBytesSent

                      totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;

 

/* Sent as the last message related to a specifictask.  Error may be

 * nil, whichimplies that no error occurred and this task is complete.

 */

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

                          didCompleteWithError:(NSError *)error;

 

@end

 

5.2.6 NSURLSessionDataDelegate

 

/*

 * Messages relatedto the operation of a task that delivers data

 * directly to thedelegate.

 */

@protocolNSURLSessionDataDelegate <NSURLSessionTaskDelegate>

@optional

/* The task has received a response and no furthermessages will be

 * received untilthe completion block is called. The disposition

 * allows you tocancel a request or to turn a data task into a

 * download task.This delegate message is optional - if you do not

 * implement it,you can get the response as a property of the task.

 *

 * This method willnot be called for background upload tasks (which cannot be converted todownload tasks).

 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask*)dataTask

                                didReceiveResponse:(NSURLResponse *)response

                                 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;

 

/* Notification that a data task has become a downloadtask.  No

 * future messageswill be sent to the data task.

 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask*)dataTask

                             didBecomeDownloadTask:(NSURLSessionDownloadTask*)downloadTask;

 

/* Sent when data is available for the delegate toconsume.  It is

 * assumed that thedelegate will retain and not copy the data. As

 * the data may bediscontiguous, you should use

 * [NSDataenumerateByteRangesUsingBlock:] to access it.

 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask*)dataTask

                                    didReceiveData:(NSData *)data;

 

/* Invoke the completion routine with a validNSCachedURLResponse to

 * allow theresulting data to be cached, or pass nil to prevent

 * caching. Notethat there is no guarantee that caching will be

 * attempted for agiven resource, and you should not rely on this

 * message toreceive the resource data.

 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask*)dataTask

                                 willCacheResponse:(NSCachedURLResponse*)proposedResponse

                                  completionHandler:(void (^)(NSCachedURLResponse*cachedResponse))completionHandler;

 

@end

 

5.2.7 NSURLSessionDownloadDelegate

 

/*

 * Messages relatedto the operation of a task that writes data to a

 * file andnotifies the delegate upon completion.

 */

@protocolNSURLSessionDownloadDelegate <NSURLSessionTaskDelegate>

 

/* Sent when a download task that has completed adownload.  The delegate should

 * copy or move thefile at the given location to a new location as it will be

 * removed when thedelegate message returns. URLSession:task:didCompleteWithError: will

 * still be called.

 */

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask*)downloadTask

                             didFinishDownloadingToURL:(NSURL *)location;

 

@optional

/* Sent periodically to notify the delegate of downloadprogress. */

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask*)downloadTask

                                          didWriteData:(int64_t)bytesWritten

                                     totalBytesWritten:(int64_t)totalBytesWritten

                             totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

 

/* Sent when a download has been resumed. If a downloadfailed with an

 * error, the-userInfo dictionary of the error will contain an

 *NSURLSessionDownloadTaskResumeData key, whose value is the resume

 * data.

 */

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask*)downloadTask

                                      didResumeAtOffset:(int64_t)fileOffset

                                    expectedTotalBytes:(int64_t)expectedTotalBytes;

 

@end

 

5.3     Session Task

Session Task分爲三種Data Task,Upload Task,Download Task。毫無疑問,Session Task是整個NSURLSession架 構的核 心目標。

注意必定要使用resume方法啓動任務。(Upload Task和Download Task同理)

 

5.3.1 建立普通的下載任務

這種下載任務是能夠取消的,代碼以下:

[objc] view plaincopy

1.  - (IBAction)cancellableDownload:(id)sender {  

2.     if (!self.cancellableTask) {  

3.          if (!self.currentSession) {  

4.             [self createCurrentSession];  

5.          }  

6.           

7.         NSString *imageURLStr = @"http://farm6.staticflickr.com/5505/9824098016_0e28a047c2_b_d.jpg";  

8.         NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];  

9.         self.cancellableTask = [self.currentSession downloadTaskWithRequest:request];  

10.          

11.         [self setDownloadButtonsWithEnabled:NO];  

12.        self.downloadedImageView.image = nil;  

13.           

14.        [self.cancellableTask resume];  

15.     }  

16.}  


若是當前的session爲空,首先須要建立一個session(該session使用默認配置模式,其delegate爲本身):

[objc] view plaincopy

1.  /* 建立當前的session */  

2. - (void)createCurrentSession {  

3.     NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];  

4.     self.currentSession = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:nil];  

5.      self.currentSession.sessionDescription = kCurrentSession;  

6. }  

隨後建立下載任務並啓動。這種任務是可取消的,即下次下載又從0.0%開始:

[objc] view plaincopy

1.  if (self.cancellableTask) {  

2.     [self.cancellableTask cancel];  

3.      self.cancellableTask = nil;  

4. }  

 

5.3.2 建立可恢復的下載任務

可恢復的下載任務支持斷點續傳,也就是若是暫停當前任務,在下次再執行任務時,將從以前的下載進度中繼續進行。所以咱們首先須要一個NSData對象來保存已經下載的數據:

[objc] view plaincopy

1.  /* 用於可恢復的下載任務的數據 */  

2. @property (strongnonatomicNSData *partialData;  

執行下載任務時,若是是恢復下載,那麼就使用downloadTaskWithResumeData:方法根據partialData繼續下載。代碼以下:

[objc] view plaincopy

1.  - (IBAction)resumableDownload:(id)sender {  

2.     if (!self.resumableTask) {  

3.          if (!self.currentSession) {  

4.             [self createCurrentSession];  

5.          }  

6.           

7.          if (self.partialData) { // 若是是以前被暫停的任務,就從已經保存的數據恢復下載  

8.             self.resumableTask = [self.currentSession downloadTaskWithResumeData:self.partialData];  

9.          }  

10.        else { // 不然建立下載任務  

11.            NSString *imageURLStr = @"http://farm3.staticflickr.com/2846/9823925914_78cd653ac9_b_d.jpg";  

12.            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];  

13.            self.resumableTask = [self.currentSession downloadTaskWithRequest:request];  

14.        }  

15.           

16.        [self setDownloadButtonsWithEnabled:NO];  

17.         self.downloadedImageView.image = nil;  

18.          

19.         [self.resumableTask resume];  

20.    }  

21. }  

在取消下載任務時,要將partialData數據保存起來,並且不要調用cancel方法:

[objc] view plaincopy

1.  else if (self.resumableTask) {  

2.     [self.resumableTask cancelByProducingResumeData:^(NSData *resumeData) {  

3.         // 若是是可恢復的下載任務,應該先將數據保存到partialData中,注意在這裏不要調用cancel方法  

4.         self.partialData = resumeData;  

5.         self.resumableTask = nil;  

6.     }];  

7.  }  

另外在恢復下載時,NSURLSessionDownloadDelegate中的如下方法將被調用:

[objc] view plaincopy

1.  /* 從fileOffset位移處恢復下載任務 */  

2. - (void)URLSession:(NSURLSession *)session  

3.        downloadTask:(NSURLSessionDownloadTask *)downloadTask  

4.  didResumeAtOffset:(int64_t)fileOffset  

5.  expectedTotalBytes:(int64_t)expectedTotalBytes {  

6.     NSLog(@"NSURLSessionDownloadDelegate: Resume download at %lld", fileOffset);  

7.  }  

 

5.3.3 建立後臺下載任務

後臺下載任務,顧名思義,當程序進入後臺後,下載任務依然繼續執行。

首先建立一個後臺session單例,這裏的Session配置使用後臺配置模式,使用backgroundSessinConfiguration:方法配置時應該經過後面的參數爲該後臺進程指定一個標識符,在有多個後臺下載任務時這個標識符就起做用了。

[objc] view plaincopy

1.  /* 建立一個後臺session單例 */  

2. - (NSURLSession *)backgroundSession {  

3.      static NSURLSession *backgroundSess = nil;  

4.     static dispatch_once_t onceToken;  

5.      dispatch_once(&onceToken, ^{  

6.         NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionID];  

7.         backgroundSess = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];  

8.         backgroundSess.sessionDescription = kBackgroundSession;  

9.      });  

10.      

11.     return backgroundSess;  

12.}  


在建立後臺下載任務時,應該使用後臺session建立,而後resume。

[objc] view plaincopy

1.  - (IBAction)backgroundDownload:(id)sender {  

2.     NSString *imageURLStr = @"http://farm3.staticflickr.com/2831/9823890176_82b4165653_b_d.jpg";  

3.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];  

4.     self.backgroundTask = [self.backgroundSession downloadTaskWithRequest:request];  

5.        

6.     [self setDownloadButtonsWithEnabled:NO];  

7.      self.downloadedImageView.image = nil;  

8.       

9.      [self.backgroundTask resume];  

10.}  


在程序進入後臺後,若是下載任務完成,程序委託中的對應方法將被回調:

[objc] view plaincopy

1.  /* 後臺下載任務完成後,程序被喚醒,該方法將被調用 */  

2. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {  

3.      NSLog(@"Application Delegate: Background download task finished");  

4.       

5.      // 設置回調的完成代碼塊  

6.     self.backgroundURLSessionCompletionHandler = completionHandler;  

7.  }  


而後調用NSURLSessionDownloadDelegate中的方法:

如下是

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL*)location中的方法,該方法只有下載成功才被調用:

[objc] view plaincopy

1.  else if (session == self.backgroundSession) {  

2.     self.backgroundTask = nil;  

3.      AppDelegate *appDelegate = [AppDelegate sharedDelegate];  

4.     if (appDelegate.backgroundURLSessionCompletionHandler) {  

5.          // 執行回調代碼塊  

6.         void (^handler)() = appDelegate.backgroundURLSessionCompletionHandler;  

7.          appDelegate.backgroundURLSessionCompletionHandler = nil;  

8.         handler();  

9.      }  

10.}  


另外不管下載成功與否,如下方法都會被調用:

[objc] view plaincopy

1.  /* 完成下載任務,不管下載成功仍是失敗都調用該方法 */  

2. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {  

3.      NSLog(@"NSURLSessionDownloadDelegate: Complete task");  

4.       

5.      dispatch_async(dispatch_get_main_queue(), ^{  

6.         [self setDownloadButtonsWithEnabled:YES];  

7.      });  

8.       

9.      if (error) {  

10.        NSLog(@"下載失敗:%@", error);  

11.         [self setDownloadProgress:0.0];  

12.        self.downloadedImageView.image = nil;  

13.     }  

14.}  


取消後臺下載任務時直接cancel便可:

[objc] view plaincopy

1.  else if (self.backgroundTask) {  

2.     [self.backgroundTask cancel];  

3.      self.backgroundTask = nil;  

4. }  

 

5.3.4 NSURLSessionDownloadDelegate

爲了實現下載進度的顯示,須要在委託中的如下方法中實現:

[objc] view plaincopy

1. /* 執行下載任務時有數據寫入 */  

2. - (void)URLSession:(NSURLSession *)session  

3.       downloadTask:(NSURLSessionDownloadTask *)downloadTask  

4.       didWriteData:(int64_t)bytesWritten // 每次寫入的data字節數  

5.  totalBytesWritten:(int64_t)totalBytesWritten // 當前一共寫入的data字節數  

6. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite // 指望收到的全部data字節數  

7.  {  

8.     // 計算當前下載進度並更新視圖  

9.     double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;  

10.    [self setDownloadProgress:downloadProgress];  

11. }  

12.  

13. /* 根據下載進度更新視圖 */  

14.- (void)setDownloadProgress:(double)progress {  

15.    NSString *progressStr = [NSString stringWithFormat:@"%.1f", progress * 100];  

16.    progressStr = [progressStr stringByAppendingString:@"%"];  

17.       

18.    dispatch_async(dispatch_get_main_queue(), ^{  

19.         self.downloadingProgressView.progress = progress;  

20.        self.currentProgress_label.text = progressStr;  

21.     });  

22.}  

 

從已經保存的數據中恢復下載任務的委託方法,fileOffset指定了恢復下載時的文件位移字節數:

[objc] view plaincopy

1.  /* Sent when a download has been resumed. If a download failed with an 

2.  * error, the -userInfo dictionary of the error will contain an 

3.   * NSURLSessionDownloadTaskResumeData key, whose value is the resume 

4.  * data.  

5.   */  

6. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  

7.                                        didResumeAtOffset:(int64_t)fileOffset  

8.                                      expectedTotalBytes:(int64_t)expectedTotalBytes;  

 

只有下載成功才調用的委託方法,在該方法中應該將下載成功後的文件移動到咱們想要的目標路徑:

[objc] view plaincopy

1. /* Sent when a download task that has completed a download.  The delegate should  

2.  * copy or move the file at the given location to a new location as it will be  

3.  * removed when the delegate message returns. URLSession:task:didCompleteWithError: will 

4.  * still be called. 

5.   */  

6. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  

7.                                didFinishDownloadingToURL:(NSURL *)location;  

 

不管下載成功或失敗都會調用的方法,相似於try-catch-finally中的finally語句塊的執行。若是下載成功,那麼error參數的值爲nil,不然下載失敗,能夠經過該參數查看出錯信息:

[objc] view plaincopy

1.  /* Sent as the last message related to a specific task.  Error may be 

2.  * nil, which implies that no error occurred and this task is complete.  

3.   */  

4. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task  

5.                             didCompleteWithError:(NSError *)error;  

 

 

6    AFURLSessionManager類

6.1    成員屬性

6.1.1  NSURLSession屬性session

@property (readonly,nonatomic,strong)NSURLSession *session;

6.1.2  線程操做隊列屬性

@property (readonly,nonatomic,strong)NSOperationQueue*operationQueue;

6.1.3  響應對象反序列化器

@property (nonatomic,strong)id <AFURLResponseSerialization> responseSerializer;

6.1.4  安全策略對象屬性

@property (nonatomic,strong)AFSecurityPolicy*securityPolicy;

6.1.5  網絡可用性檢查對象屬性

@property (readwrite,nonatomic,strong)AFNetworkReachabilityManager*reachabilityManager;

6.1.6  任務數組

/**

 The data, upload,and download tasks currently run by the managed session.

 */

@property (readonly,nonatomic,strong)NSArray *tasks;

6.1.7  數據請求任務數組

/**

 The data taskscurrently run by the managed session.

 */

@property (readonly,nonatomic,strong)NSArray *dataTasks;

6.1.8  上傳任務數組

/**

 The upload taskscurrently run by the managed session.

 */

@property (readonly,nonatomic,strong)NSArray *uploadTasks;

6.1.9  下載任務數組

/**

 The download taskscurrently run by the managed session.

 */

@property (readonly,nonatomic,strong)NSArray *downloadTasks;

 

6.1.10             請求完成後線程隊列

///-------------------------------

/// @name Managing Callback Queues

///-------------------------------

 

/**

 The dispatch queuefor `completionBlock`. If `NULL` (default), the main queue is used.

 */

@property (nonatomic,strong)dispatch_queue_tcompletionQueue;

6.1.11             請求完成後block羣組

/**

 The dispatch groupfor `completionBlock`. If `NULL` (default), a private dispatch group is used.

 */

@property (nonatomic,strong)dispatch_group_tcompletionGroup;

 

///---------------------------------

/// @name Working Around System Bugs

///---------------------------------

6.1.12             是否嘗試從新建立任務項屬性

/**

 Whether to attemptto retry creation of upload tasks for background sessions when initial callreturns `nil`. `NO` by default.

 

 @bugAs of iOS 7.0,there is a bug where upload tasks created for background tasks are sometimes`nil`. As a workaround, if this property is `YES`, AFNetworking will followApple's recommendation to try creating the task again.

 

 @seehttps://github.com/AFNetworking/AFNetworking/issues/1675

 */

@property(nonatomic,assign)BOOLattemptsToRecreateUploadTasksForBackgroundSessions;

 

6.2     成員方法

6.2.1  初始化方法

/**

 Creates andreturns a manager for a session created with the specified configuration. Thisis the designated initializer.

 

 @param configurationThe configuration used to create the managed session.

 

 @return A manager fora newly-created session.

 */

- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration*)configuration;

6.2.2  結束Session方法

/**

 Invalidates themanaged session, optionally canceling pending tasks.

 

 @paramcancelPendingTasks Whether or not to cancel pending tasks.

 */

- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;

 

6.2.3  根據URL請求新建NSURLSessionDataTask方法

/**

 Creates an`NSURLSessionDataTask` with the specified request.

 

 @param request TheHTTP request for the request.

 @paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.

 */

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request

                            completionHandler:(void (^)(NSURLResponse*response,idresponseObject,NSError *error))completionHandler;

6.2.4 【上傳】根據本地文件新建NSURLSessionUploadTask對象的方法

/**

 Creates an`NSURLSessionUploadTask` with the specified request for a local file.

 

 @param request TheHTTP request for the request.

 @param fileURL A URLto the local file to be uploaded.

 @param progress Aprogress object monitoring the current upload progress.

 @paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.

 

 @see`attemptsToRecreateUploadTasksForBackgroundSessions`

 */

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request

                                        fromFile:(NSURL *)fileURL

                                         progress:(NSProgress*__autoreleasing*)progress

                               completionHandler:(void (^)(NSURLResponse*response,id responseObject,NSError *error))completionHandler;

6.2.5 【上傳】根據二級制數據新建NSURLSessionUploadTask對象的方法

/**

 Creates an`NSURLSessionUploadTask` with the specified request for an HTTP body.

 

 @param request TheHTTP request for the request.

 @param bodyData Adata object containing the HTTP body to be uploaded.

 @param progress Aprogress object monitoring the current upload progress.

 @paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.

 */

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request

                                        fromData:(NSData *)bodyData

                                        progress:(NSProgress *__autoreleasing*)progress

                               completionHandler:(void (^)(NSURLResponse*response,id responseObject,NSError *error))completionHandler;

6.2.6 【上傳】根據流數據新建NSURLSessionUploadTask對象的方法

/**

 Creates an`NSURLSessionUploadTask` with the specified streaming request.

 

 @param request TheHTTP request for the request.

 @param progress Aprogress object monitoring the current upload progress.

 @paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.

 */

- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request

                                                progress:(NSProgress*__autoreleasing *)progress

                                       completionHandler:(void (^)(NSURLResponse*response,id responseObject,NSError *error))completionHandler;

6.2.7 【下載】根據URL請求新建NSURLSessionDownloadTask對象的方法

/**

 Creates an `NSURLSessionDownloadTask`with the specified request.

 

 @param request TheHTTP request for the request.

 @param progress Aprogress object monitoring the current download progress.

 @paramdestination Ablock object to be executed in order to determine the destination of thedownloaded file. This block takes two arguments, the target path & theserver response, and returns the desired file URL of the resulting download.The temporary file used during the download will be automatically deleted afterbeing moved to the returned URL.

 @paramcompletionHandler A block to be executed when a task finishes. This block hasno return value and takes three arguments: the server response, the path of thedownloaded file, and the error describing the network or parsing error thatoccurred, if any.

 

 @warningIf using abackground `NSURLSessionConfiguration` on iOS, these blocks will be lost whenthe app is terminated. Background sessions may prefer to use`-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving thedownloaded file, rather than the destination block of this method.

 */

- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request

                                            progress:(NSProgress *__autoreleasing*)progress

                                         destination:(NSURL * (^)(NSURL*targetPath,NSURLResponse *response))destination

                                   completionHandler:(void (^)(NSURLResponse*response,NSURL *filePath,NSError *error))completionHandler;

6.2.8 【下載】根據二進制數據新建NSURLSessionDownloadTask對象的方法

/**

 Creates an`NSURLSessionDownloadTask` with the specified resume data.

 

 @param resumeData Thedata used to resume downloading.

 @param progress Aprogress object monitoring the current download progress.

 @paramdestination Ablock object to be executed in order to determine the destination of thedownloaded file. This block takes two arguments, the target path & theserver response, and returns the desired file URL of the resulting download.The temporary file used during the download will be automatically deleted afterbeing moved to the returned URL.

 @paramcompletionHandler A block to be executed when a task finishes. This block hasno return value and takes three arguments: the server response, the path of thedownloaded file, and the error describing the network or parsing error thatoccurred, if any.

 */

- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData

                                               progress:(NSProgress*__autoreleasing *)progress

                                            destination:(NSURL * (^)(NSURL*targetPath,NSURLResponse *response))destination

                                      completionHandler:(void (^)(NSURLResponse*response,NSURL *filePath,NSError *error))completionHandler;

 

6.2.9  獲取上傳進度方法

/**

 Returns the uploadprogress of the specified task.

 

 @param uploadTask Thesession upload task. Must not be `nil`.

 

 @return An`NSProgress` object reporting the upload progress of a task, or `nil` if theprogress is unavailable.

 */

- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask;

6.2.10             獲取下載進度方法

/**

 Returns thedownload progress of the specified task.

 

 @param downloadTaskThe session download task. Must not be `nil`.

 

 @return An`NSProgress` object reporting the download progress of a task, or `nil` if theprogress is unavailable.

 */

- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask;

 

///-----------------------------------------

/// @name Setting Session Delegate Callbacks

///-----------------------------------------

6.2.11             設置Session失效時執行block

/**

 Sets a block to beexecuted when the managed session becomes invalid, as handled by the`NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.

 

 @param block A blockobject to be executed when the managed session becomes invalid. The block hasno return value, and takes two arguments: the session, and the error related tothe cause of invalidation.

 */

- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session,NSError*error))block;

6.2.12             設置發送認證時執行的block

/**

 Sets a block to beexecuted when a connection level authentication challenge has occurred, ashandled by the `NSURLSessionDelegate` method`URLSession:didReceiveChallenge:completionHandler:`.

 

 @paramblock A blockobject to be executed when a connection level authentication challenge hasoccurred. The block returns the disposition of the authentication challenge,and takes three arguments: the session, the authentication challenge, and apointer to the credential that should be used to resolve the challenge.

 */

- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession*session,NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential))block;

6.2.13             設置任務請求新流數據包時執行的block

/**

 Sets a block to beexecuted when a task requires a new request body stream to send to the remoteserver, as handled by the `NSURLSessionTaskDelegate` method`URLSession:task:needNewBodyStream:`.

 

 @param block A blockobject to be executed when a task requires a new request body stream.

 */

- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession*session,NSURLSessionTask *task))block;

6.2.14             設置請求重定向時執行的block

/**

Sets a block to beexecuted when an HTTP request is attempting to perform a redirection to adifferent URL, as handled by the `NSURLSessionTaskDelegate` method`URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.

 

 @paramblock A blockobject to be executed when an HTTP request is attempting to perform aredirection to a different URL. The block returns the request to be made forthe redirection, and takes four arguments: the session, the task, theredirection response, and the request corresponding to the redirectionresponse.

 */

- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession*session,NSURLSessionTask *task, NSURLResponse *response, NSURLRequest*request))block;

6.2.15             設置認證請求完成時執行的block

/**

Sets a block to beexecuted when a session task has received a request specific authenticationchallenge, as handled by the `NSURLSessionTaskDelegate` method`URLSession:task:didReceiveChallenge:completionHandler:`.

 

 @paramblock A blockobject to be executed when a session task has received a request specificauthentication challenge. The block returns the disposition of theauthentication challenge, and takes four arguments: the session, the task, theauthentication challenge, and a pointer to the credential that should be usedto resolve the challenge.

 */

- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session,NSURLSessionTask*task, NSURLAuthenticationChallenge *challenge,NSURLCredential *__autoreleasing*credential))block;

6.2.16             設置跟蹤上傳進度時執行的block

/**

 Sets a block to beexecuted periodically to track upload progress, as handled by the`NSURLSessionTaskDelegate` method`URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.

 

 @paramblock A blockobject to be called when an undetermined number of bytes have been uploaded tothe server. This block has no return value and takes five arguments: thesession, the task, the number of bytes written since the last time the uploadprogress block was called, the total bytes written, and the total bytesexpected to be written during the request, as initially determined by thelength of the HTTP body. This block may be called multiple times, and willexecute on the main thread.

 */

- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession*session,NSURLSessionTask *task,int64_t bytesSent, int64_ttotalBytesSent,int64_ttotalBytesExpectedToSend))block;

6.2.17             設置任務接收完最後一條消息後執行的block

/**

 Sets a block to beexecuted as the last message related to a specific task, as handled by the`NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.

 

 @paramblock A blockobject to be executed when a session task is completed. The block has no returnvalue, and takes three arguments: the session, the task, and any error thatoccurred in the process of executing the task.

 */

- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session,NSURLSessionTask*task,NSError *error))block;

 

///-------------------------------------------

/// @name Setting Data Task Delegate Callbacks

///-------------------------------------------

6.2.18             設置DataTask接收到響應時執行的block

/**

 Sets a block to beexecuted when a data task has received a response, as handled by the`NSURLSessionDataDelegate` method`URLSession:dataTask:didReceiveResponse:completionHandler:`.

 

 @paramblock A blockobject to be executed when a data task has received a response. The blockreturns the disposition of the session response, and takes three arguments: thesession, the data task, and the received response.

 */

- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session,NSURLSessionDataTask *dataTask, NSURLResponse*response))block;

6.2.19             設置當一個DataTask轉化爲DownloadTask時執行的block

/**

 Sets a block to beexecuted when a data task has become a download task, as handled by the`NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.

 

 @paramblock A blockobject to be executed when a data task has become a download task. The blockhas no return value, and takes three arguments: the session, the data task, andthe download task it has become.

 */

- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession*session,NSURLSessionDataTask *dataTask,NSURLSessionDownloadTask*downloadTask))block;

6.2.20             設置當一個DataTask收到數據時執行的block

/**

 Sets a block to beexecuted when a data task receives data, as handled by the`NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.

 

 @paramblock A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes three arguments: thesession, the data task, and the data received. This block may be calledmultiple times, and will execute on the session manager operation queue.

 */

- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession*session,NSURLSessionDataTask *dataTask,NSData *data))block;

6.2.21             設置肯定一個DataTask的緩存方式時執行的block

/**

 Sets a block to beexecuted to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate`method `URLSession:dataTask:willCacheResponse:completionHandler:`.

 

 @paramblock A blockobject to be executed to determine the caching behavior of a data task. Theblock returns the response to cache, and takes three arguments: the session,the data task, and the proposed cached URL response.

 */

- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession*session,NSURLSessionDataTask *dataTask, NSCachedURLResponse*proposedResponse))block;

6.2.22             設置當全部消息都傳輸完成時執行的block

/**

 Sets a block to beexecuted once all messages enqueued for a session have been delivered, ashandled by the `NSURLSessionDataDelegate` method`URLSessionDidFinishEventsForBackgroundURLSession:`.

 

 @param block A blockobject to be executed once all messages enqueued for a session have beendelivered. The block has no return value and takes a single argument: thesession.

 */

- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession*session))block;

6.2.23             設置下載完成時執行的block

///-----------------------------------------------

/// @name Setting Download Task Delegate Callbacks

///-----------------------------------------------

 

/**

 Sets a block to beexecuted when a download task has completed a download, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didFinishDownloadingToURL:`.

 

 @paramblock A blockobject to be executed when a download task has completed. The block returns theURL the download should be moved to, and takes three arguments: the session, thedownload task, and the temporary location of the downloaded file. If the filemanager encounters an error while attempting to move the temporary file to thedestination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will beposted, with the download task as its object, and the user info of the error.

 */

- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession*session,NSURLSessionDownloadTask *downloadTask, NSURL *location))block;

6.2.24             設置跟蹤下載進度時執行的block

/**

Sets a block to beexecuted periodically to track download progress, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.

 

 @paramblock A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes five arguments: thesession, the download task, the number of bytes read since the last time thedownload progress block was called, the total bytes read, and the total bytesexpected to be read during the request, as initially determined by the expectedcontent size of the `NSHTTPURLResponse` object. This block may be calledmultiple times, and will execute on the session manager operation queue.

 */

- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession*session,NSURLSessionDownloadTask *downloadTask,int64_t bytesWritten, int64_ttotalBytesWritten, int64_t totalBytesExpectedToWrite))block;

6.2.25             設置DownloadTask恢復下載時執行的block

/**

 Sets a block to beexecuted when a download task has been resumed, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.

 

 @paramblock A blockobject to be executed when a download task has been resumed. The block has noreturn value and takes four arguments: the session, the download task, the fileoffset of the resumed download, and the total number of bytes expected to bedownloaded.

 */

- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession*session,NSURLSessionDownloadTask *downloadTask,int64_t fileOffset, int64_texpectedTotalBytes))block;

 

7    AFHTTPSessionManager類

7.1     成員屬性

7.1.1  域名或頂級目錄URL屬性

/**

 The URL used tomonitor reachability, and construct requests from relative paths in methodslike `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al.convenience methods.

 */

@property (readonly,nonatomic,strong)NSURL *baseURL;

7.1.2  AFHTTP請求序列號器對象屬性

/**

Requests createdwith `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`are constructed with a set of default headers using a parameter serializationspecified by this property. By default, this is set to an instance of`AFHTTPRequestSerializer`, which serializes query string parameters for `GET`,`HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP messagebodies.

 

 @warning`requestSerializer` must not be `nil`.

 */

@property (nonatomic,strong)AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;

7.1.3  AFHTTP響應序列號器對象屬性

/**

Responses sentfrom the server in data tasks created with`dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / etal. convenience methods are automatically validated and serialized by theresponse serializer. By default, this property is set to an instance of`AFJSONResponseSerializer`.

 

 @warning`responseSerializer` must not be `nil`.

 */

@property (nonatomic,strong)AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

 

7.2     成員方法

7.2.1  單例方法

/**

 Creates andreturns an `AFHTTPSessionManager` object.

 */

+ (instancetype)manager;

7.2.2  初始化方法

/**

 Initializes an`AFHTTPSessionManager` object with the specified base URL.

 

 @param url The baseURL for the HTTP client.

 

 @return The newly-initializedHTTP client

 */

- (instancetype)initWithBaseURL:(NSURL *)url;

 

/**

 Initializes an`AFHTTPSessionManager` object with the specified base URL.

 

 This is thedesignated initializer.

 

 @param url The baseURL for the HTTP client.

 @param configurationThe configuration used to create the managed session.

 

 @return Thenewly-initialized HTTP client

 */

- (instancetype)initWithBaseURL:(NSURL *)url

          sessionConfiguration:(NSURLSessionConfiguration *)configuration;

7.2.3  Get請求方法

/**

 Creates and runs an`NSURLSessionDataTask` with a `GET` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)GET:(NSString *)URLString

                  parameters:(id)parameters

                     success:(void (^)(NSURLSessionDataTask *task,idresponseObject))success

                     failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.4  Head請求方法

/**

 Creates and runsan `NSURLSessionDataTask` with a `HEAD` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes a single arguments: the data task.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)HEAD:(NSString *)URLString

                   parameters:(id)parameters

                      success:(void (^)(NSURLSessionDataTask *task))success

                      failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.5  Post請求方法

/**

 Creates and runsan `NSURLSessionDataTask` with a `POST` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)POST:(NSString *)URLString

                   parameters:(id)parameters

                      success:(void (^)(NSURLSessionDataTask *task,idresponseObject))success

                      failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.6  Post請求方法2

/**

 Creates and runsan `NSURLSessionDataTask` with a multipart `POST` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @param block A blockthat takes a single argument and appends data to the HTTP body. The blockargument is an object adopting the `AFMultipartFormData` protocol.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)POST:(NSString *)URLString

                   parameters:(id)parameters

    constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block

                      success:(void (^)(NSURLSessionDataTask *task,idresponseObject))success

                      failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.7  Put請求方法

/**

 Creates and runsan `NSURLSessionDataTask` with a `PUT` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)PUT:(NSString *)URLString

                  parameters:(id)parameters

                     success:(void (^)(NSURLSessionDataTask *task,idresponseObject))success

                      failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.8  Patch請求方法

/**

 Creates and runsan `NSURLSessionDataTask` with a `PATCH` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)PATCH:(NSString *)URLString

                    parameters:(id)parameters

                       success:(void (^)(NSURLSessionDataTask*task,idresponseObject))success

                       failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

7.2.9  Delete請求方法

/**

 Creates and runsan `NSURLSessionDataTask` with a `DELETE` request.

 

 @param URLString TheURL string used to create the request URL.

 @param parameters Theparameters to be encoded according to the client request serializer.

 @paramsuccess Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.

 @paramfailure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.

 

 @see-dataTaskWithRequest:completionHandler:

 */

- (NSURLSessionDataTask *)DELETE:(NSString *)URLString

                     parameters:(id)parameters

                        success:(void (^)(NSURLSessionDataTask *task,idresponseObject))success

                        failure:(void (^)(NSURLSessionDataTask *task,NSError*error))failure;

 

8    參考連接

AFNetworking Class References

http://cocoadocs.org/docsets/AFNetworking/2.4.1/

 

AFNetworking速成教程

http://blog.csdn.net/ysysbaobei/article/details/17390639

 

NSURLSession學習筆記(一)簡介

http://blog.csdn.net/majiakun1/article/details/38133433

 

NSURLSession學習筆記(二)Session Task

http://blog.csdn.net/majiakun1/article/details/38133703

 

AFNetworking 學習筆記

http://blog.csdn.net/ysysbaobei/article/details/17390969

 

NSOperation

http://nshipster.com/nsoperation/

 

AFNetworking 2.0簡介

https://github.com/NSHipster/articles/blob/zh-Hans/2013-09-16-afnetworking-2.md#afnetworking-%E7%9A%84%E5%A4%A7%E4%BD%93%E6%80%9D%E8%B7%AF

相關文章
相關標籤/搜索