這篇文章會有什么?
在這篇文章中把NSURLSession.h文件集體梳理一遍,把里面的每個屬性、代理和方法都拿出來說說,通過這篇文章我相信對於NSURLSession這一塊的東西會梳理的比較全面一點,你掌握了NSURLSession對於iOS網絡處理理解的就會有點深度了,而不是停留在AF的層面,理解了NSURLSession再去看AFNetWorking的源碼會有很大的幫助。 最后再通過最后面一個Demo,把NSURLSession的一些日常中的使用再過一遍,包括你經常會聽到的后台下載、斷點下載、斷點續傳等等都有代碼介紹。
在這里我們再順便說說NSURLRequest,因為你在能看到NSURLSession的地方肯定能看到NSURLRequest。下面我們就從NSURLRequest開始總結。
NSURLRequest
關於NSURLRequest基本的用法這里不再討論,相信都了解,我們直接看看它的API,還是喜歡從API入手了解一個類。
當然,我們也不用每一個屬性那樣去解釋,有些的確是太簡單了,直接從感覺需要我們梳理一下的地方入手,具體的每一個屬性建議大家自己去看看頭文件了解。
下面說的點對着這NSURLRequest頭文件更容易理解:
/*! @method requestWithURL:cachePolicy:timeoutInterval: @abstract Allocates and initializes a NSURLRequest with the given URL and cache policy. @param URL The URL for the request. @param cachePolicy The cache policy for the request. @param timeoutInterval The timeout interval for the request. See the commentary for the <tt>timeoutInterval</tt> for more information on timeout intervals. @result A newly-created and autoreleased NSURLRequest instance. 這個是類方法的初始化方法,參數就是緩存策略和超時時間 這里引入了這個NSURLRequestCachePolicy緩存策略的枚舉類型,下面梳理這個枚舉。 typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy) { 默認緩存策略 NSURLRequestUseProtocolCachePolicy = 0, URL應該加載源端數據,不使用本地緩存數據 NSURLRequestReloadIgnoringLocalCacheData = 1, 本地緩存數據、代理和其他中介都要忽視他們的緩存,直接加載源數據 NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented 從服務端加載數據,完全忽略緩存。和NSURLRequestReloadIgnoringLocalCacheData一樣 NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, 使用緩存數據,忽略其過期時間;只有在沒有緩存版本的時候才從源端加載數據 NSURLRequestReturnCacheDataElseLoad = 2, 只使用cache數據,如果不存在cache,就請求失敗,不再去請求數據 用於沒有建立網絡連接離線模式 NSURLRequestReturnCacheDataDontLoad = 3, 指定如果已存的緩存數據被提供它的源段確認為有效則允許使用緩存數據響應請求,否則從源段加載數據。 NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented }; */ + (instancetype)requestWithURL:(NSURL *)URL cachePolicy:(NSURLRequestCachePolicy)cachePolicy timeoutInterval:(NSTimeInterval)timeoutInterval;
我們再接着往下看:
這里說一下NS_DESIGNATED_INITIALIZER 和 NS_UNAVAILABLE 這兩個宏,這兩個宏相信你要是經常看頭文件的話是很容易碰到的。
/*! @abstract Returns the cache policy of the receiver. @result The cache policy of the receiver. 緩存策略 */ @property (readonly) NSURLRequestCachePolicy cachePolicy; /*! @abstract Returns the timeout interval of the receiver. @discussion The timeout interval specifies the limit on the idle interval alloted to a request in the process of loading. The "idle interval" is defined as the period of time that has passed since the last instance of load activity occurred for a request that is in the process of loading. Hence, when an instance of load activity occurs (e.g. bytes are received from the network for a request), the idle interval for a request is reset to 0. If the idle interval ever becomes greater than or equal to the timeout interval, the request is considered to have timed out. This timeout interval is measured in seconds. @result The timeout interval of the receiver. 請求超時時間 */ @property (readonly) NSTimeInterval timeoutInterval; /*! @abstract The main document URL associated with this load. @discussion This URL is used for the cookie "same domain as main document" policy. There may also be other future uses. See setMainDocumentURL: NOTE: In the current implementation, this value is unused by the framework. A fully functional version of this method will be available in the future. @result The main document URL. 主文檔地址 這個地址用來存放緩存 */ @property (nullable, readonly, copy) NSURL *mainDocumentURL; /*! @abstract Returns the NSURLRequestNetworkServiceType associated with this request. @discussion This will return NSURLNetworkServiceTypeDefault for requests that have not explicitly set a networkServiceType (using the setNetworkServiceType method). @result The NSURLRequestNetworkServiceType associated with this request. 獲取網絡請求的服務類型 枚舉如下 */ @property (readonly) NSURLRequestNetworkServiceType networkServiceType API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)); /*! @abstract returns whether a connection created with this request is allowed to use the built in cellular radios (if present). @result YES if the receiver is allowed to use the built in cellular radios to satify the request, NO otherwise. 獲取是否允許使用服務商蜂窩網絡 */ @property (readonly) BOOL allowsCellularAccess API_AVAILABLE(macos(10.8), ios(6.0), watchos(2.0), tvos(9.0));
NSURLRequest還有一個NSHTTPURLRequest的類別,這個類別對於我們自定義請求頭請求體這些的時候是很重要的,我們先看看這個類別里面有什么:
/*! HTTP請求方式 POST GET 等 */ @property (nullable, readonly, copy) NSString *HTTPMethod; /*! 得到一個字典數據,設置的 HTTP請求頭的鍵值數據 */ @property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields; /*! 設置http請求頭中的字段值,這個我們待會在看看一些Demo代碼和AF的源碼比較一下 */ - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; /*! 請求體 */ @property (nullable, readonly, copy) NSData *HTTPBody; /*! http請求體的輸入流 */ @property (nullable, readonly, retain) NSInputStream *HTTPBodyStream; /*! 設置發送請求時是否發送cookie數據 */ @property (readonly) BOOL HTTPShouldHandleCookies; /*! 設置的請求時是否按順序收發 默認禁用 在某些服務器中設為YES可以提高網絡性能 */ @property (readonly) BOOL HTTPShouldUsePipelining API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)); /*! 設置http請求頭中的字段值 */ - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field; /*! 向http請求頭中添加一個字段 */ - (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
可以看到這個類別全都是關於請求體和請求頭的一些設置方法以及屬性,既然這里我們說到了這兩個東西,我們也說說,下面是我們常見的額請求頭設置屬性:
Host: 目標服務器的網絡地址
Accept: 讓服務端知道客戶端所能接收的數據類型,如text/html
Content-Type: body中的數據類型,如application/json; charset=UTF-8
Accept-Language: 客戶端的語言環境,如zh-cn
Accept-Encoding: 客戶端支持的數據壓縮格式,如gzip
User-Agent: 客戶端的軟件環境,我們可以更改該字段為自己客戶端的名字,比如QQ music v1.11,比如瀏覽器Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Maxthon/4.5.2
Connection: keep-alive,該字段是從HTTP 1.1才開始有的,用來告訴服務端這是一個持久連接,“請服務端不要在發出響應后立即斷開TCP連接”。關於該字段的更多解釋將在后面的HTTP版本簡介中展開。
Content-Length: body的長度,如果body為空則該字段值為0。該字段一般在POST請求中才會有。
再說說請求體,請求體的封裝我們用一張圖告訴大家:(文頂頂博客轉載)
要是大家接觸過這方面的內容理解上面我們說的請求體和請求頭就相對容易一點,但要是完全沒有機會接觸過,可能就會不知道上面這一段內容說的是什么,其實他們在我們處理文件上傳的時候能用到,在以前我關於Telegram寫的怎樣在它的基礎上增加自己得網絡請求的時候,在涉及到文件上傳這一塊有用到過,這里給兩篇博客鏈接,供大家參考學習一下這個請求頭和請求體的設置(我記得這個問題我以前面試過的時候有人問過我,可惜...那時候我接觸開發不懂這些呀....哈哈)
最后,再說一點上面的關於這個 -- 上傳文件的 MIMEType,這個在以前我也有說過,當然這些內容我也會在下面的Demo中體現一下的。
NSURLSession
在說這個之前,我們先看一張圖梳理一下他們之間的整體關系(此文的圖都是同行博客中收集的,感謝感謝!)
接着我們說我們要理解的重點--NSURLSession,下面的內容是按照NSURLSession.h API來寫的,你可以對比着來看。先看看NSURLSession:
/* NSURLSession 默認是掛起的狀態,要是需要網絡請求需要去開啟, 下面這個屬性sharedSession就是獲取全局的NSURLSession對象。在iPhone的所有app共用一個全局session。 @property (class, readonly, strong) NSURLSession * sharedSession; */ /* * Customization of NSURLSession occurs during creation of a new session. * If you only need to use the convenience routines with custom * configuration options it is not necessary(必要的) to specify(特殊的) a delegate. * If you do specify a delegate, the delegate will be retained(保留) until after * the delegate has been sent the URLSession:didBecomeInvalidWithError: message. 代理一直會被保留,直到代理接收到URLSession:didBecomeInvalidWithError:消息 下面兩個是利用NSURLSessionConfiguration對象得到NSURLSession的方法,區別在於代理的設置 + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration; + (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate delegateQueue:(nullable NSOperationQueue *)queue; */ /* * 下面這三個都是只讀屬性,意義明確,不需要再解釋 * @property (readonly, retain) NSOperationQueue *delegateQueue; * @property (nullable, readonly, retain) id <NSURLSessionDelegate> delegate; * @property (readonly, copy) NSURLSessionConfiguration *configuration; */ /* * The sessionDescription property is available for the developer to * provide a descriptive label for the session. * 該方法是給session添加一個描述信息 * @property (nullable, copy) NSString *sessionDescription; */ /* -finishTasksAndInvalidate returns immediately and existing tasks will be allowed * to run to completion. New tasks may not be created. The session * will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError: * has been issued. * * -finishTasksAndInvalidate and -invalidateAndCancel do not * have any effect on the shared session singleton. * * When invalidating a background session, it is not safe to create another background * session with the same identifier until URLSession:didBecomeInvalidWithError: has * been issued. 這個方法是任務完成之后調用會釋放session 這里涉及到的是session和代理之間相互的強引用可能會造成內存泄漏的問題,了解一下! - (void)finishTasksAndInvalidate; */ /* -invalidateAndCancel acts as -finishTasksAndInvalidate, but issues * -cancel to all outstanding tasks for this session. Note task * cancellation is subject to the state of the task, and some tasks may * have already have completed at the time they are sent -cancel. 這個是取消任務釋放session 和前面的任務完成之后是有區別的,上面的注釋又給我們解釋說讓我們注意任務的狀態 可能會給一些結束的任務發送cancel消息 - (void)invalidateAndCancel; NOTE:當對 session invalidate 后,就不能再創建新的 task 了,兩個方法的不同之處是,- finishTasksAndInvalidate會等到正在執行的 task 執行完成,調用完所有回調或 delegate 后,釋放對 delegate 的強引用,而- invalidateAndCancel方法則是直接取消所有正在執行的 task。 */ /* 清空所有的 cookie、緩存、證書等,傳入的 completionHandler 在上述操作完成后執行。 empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil. - (void)resetWithCompletionHandler:(void (^)(void))completionHandler; */ /* 將內存中的 cookie、證書等寫到硬盤,之后的請求會使用新的 TCP 連接,傳入的 completionHandler 在上述操作完成后執行。 storage to disk 存儲到磁盤 flush storage to disk and clear transient network caches. Invokes completionHandler() on the delegate queue if not nil. - (void)flushWithCompletionHandler:(void (^)(void))completionHandler; */ /* 獲取 session 中的 task,在獲取完 task 列表后會執行傳入的 completionHandler 參數,而 task 列表則作為 block 的參數傳入。*/ /* invokes completionHandler with outstanding data, upload and download tasks. - (void)getTasksWithCompletionHandler:(void (^)(NSArray<NSURLSessionDataTask *> *dataTasks, NSArray<NSURLSessionUploadTask *> *uploadTasks, NSArray<NSURLSessionDownloadTask *> *downloadTasks))completionHandler; */ /* invokes completionHandler with all outstanding tasks. - (void)getAllTasksWithCompletionHandler:(void (^)(NSArray<__kindof NSURLSessionTask *> *tasks))completionHandler API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)); */ /* * NSURLSessionTask objects are always created in a suspended state (suspend 和 pause 表示暫停 掛起狀態) and * must be sent the -resume message before they will execute. */ //下面的額這些方法都是用來初始化Task的 //當然這個Task就包括dataTask,uploadTask/downloadTask。以及streamTask。。 /* 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 the given URL. - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url; */ /* Creates an upload task with the given request. The body of the request will be created from the 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 the bodyData. - (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 be called 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 of the 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; */ /* Creates a bidirectional stream (雙向) task to a given host and port. - (NSURLSessionStreamTask *)streamTaskWithHostName:(NSString *)hostname port:(NSInteger)port API_AVAILABLE(macos(10.11), ios(9.0), tvos(9.0)) __WATCHOS_PROHIBITED; */ /* Creates a bidirectional stream task with an NSNetService to identify the endpoint. * The NSNetService will be resolved before any IO completes. - (NSURLSessionStreamTask *)streamTaskWithNetService:(NSNetService *)service API_AVAILABLE(macos(10.11), ios(9.0), tvos(9.0)) __WATCHOS_PROHIBITED; */
在API接下來中應該是NSURLSessionAsynchronousConvenience這個NSURLSession的類別,但這個比較簡單,它只是在上面我們提到的Task初始化的基礎上加上了一個completionHandler的block,也就是一個初始化完成的block,關於這我們也就不再多說了。
接着往下面看,再往下就是NSURLSessionTask這個比較核心的類了,后面我們說的四個類(data/upload/download/stream)Task ,其中data、download、stream是繼承自我們要說的NSURLSessionTask這個核心。 而我們的上傳upload是繼承自data,這個也不難理解!這三個類封裝了現代應用程序的三個基本網絡任務:獲取數據,比如JSON/XML,以及上傳和下載文件。下面是我們對這些API的理解:
我們也是用過這張看看Task之間的關系:
嗯,就從最基本的NSURLSessionTask的API開始說起:
/* @interface NSURLSessionTask : NSObject <NSCopying, NSProgressReporting> @property (readonly) NSUInteger taskIdentifier; an identifier for this task, assigned by and unique to the owning session @property (nullable, readonly, copy) NSURLRequest *originalRequest; may be nil if this is a stream task @property (nullable, readonly, copy) NSURLRequest *currentRequest; may differ from originalRequest due to http server redirection // 服務器對當前活動請求的響應 @property (nullable, readonly, copy) NSURLResponse *response; may be nil if no response has been received * NSProgress object which represents the task progress. * It can be used for task progress tracking. 進度 @property (readonly, strong) NSProgress *progress API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); 網絡負載應該開始的最早日期 對於從后台NSURLSession實例創建的任務,此屬性表示網絡負載不應該在此日期之前開始。 設置此屬性並不能保證加載將從指定的日期開始,而只是它不會馬上開始。 如果未指定,則不使用啟動延遲。 此屬性對從非后台會話創建的任務沒有影響。 * Start the network load for this task no earlier than the specified date. If * not specified, no start delay is used. * 只適用於后台NSURLSession * Only applies to tasks created from background NSURLSession instances; has no * effect for tasks created from other session types. @property (nullable, copy) NSDate * earliestBeginDate API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); 下面這兩個屬性其實是比較重要的,兩個解釋分貝如下: 1、客戶期望發送的字節數的期待上限。 為此屬性設置的值應考慮HTTP頭和正文數據或正文流的大小。如果未指定值,則系統將使用NSURLSessionTransferSizeUnknown。該屬性由系統用來優化URL會話任務的調度。強烈建議開發人員盡可能提供近似的上限或確切的字節數,而不是接受默認值。 2、客戶期望接收的字節數的期待上限。 為此屬性設置的值應考慮HTTP響應頭和響應主體的大小。如果未指定值,則系統將使用NSURLSessionTransferSizeUnknown。該屬性由系統用來優化URL會話任務的調度。強烈建議開發人員盡可能提供近似的上限或確切的字節數,而不是接受默認值。 * The number of bytes that the client expects (a best-guess upper-bound) will * be sent and received by this task. These values are used by system scheduling * policy. If unspecified, NSURLSessionTransferSizeUnknown is used. @property int64_t countOfBytesClientExpectsToSend API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); @property int64_t countOfBytesClientExpectsToReceive API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)); * Byte count properties may be zero if no body is expected, * or NSURLSessionTransferSizeUnknown if it is not possible * to know how many bytes will be transferred. // 實際發送和接受的字節 number of body bytes already received @property (readonly) int64_t countOfBytesReceived; number of body bytes already sent @property (readonly) int64_t countOfBytesSent; //預計發生的數據,和 Content-Length of the HTTP request 有關 number of body bytes we expect to send, derived from the Content-Length of the HTTP request @property (readonly) int64_t countOfBytesExpectedToSend; //預計接收,通常來自HTTP響應的內容長度標題。 number of byte bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. @property (readonly) int64_t countOfBytesExpectedToReceive; 該任務描述 * The taskDescription property is available for the developer to * provide a descriptive label for the task. @property (nullable, copy) NSString *taskDescription; -cancel returns immediately, but marks a task as being canceled. * The task will signal -URLSession:task:didCompleteWithError: with an * error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some * cases, the task may signal other work before it acknowledges the * cancelation. -cancel may be sent to a task that has been suspended. 將任務標記為取消 - (void)cancel; 當前任務的狀態 * The current state of the task within the session. @property (readonly) NSURLSessionTaskState state; 錯誤 * The error, if any, delivered via -URLSession:task:didCompleteWithError: * This property will be nil in the event that no error occured. @property (nullable, readonly, copy) NSError *error; 暫停/恢復 - (void)suspend; - (void)resume; 任務優先級 @property float priority API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); @end 下面就是前面說的優先級的值 FOUNDATION_EXPORT const float NSURLSessionTaskPriorityDefault API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT const float NSURLSessionTaskPriorityLow API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); FOUNDATION_EXPORT const float NSURLSessionTaskPriorityHigh API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0));
上面我們說了這個NSURLSessionTask還要三個子類,在API中前面的兩個子類我就沒有什么還能說的了,因為都包含在了NSURLSessionTask中,唯一有一個需要我們說一下的,就是在NSURLSessionDownloadTask中有一個方法是父類中沒有的,我們看看對這個方法的理解:
* 取消下載 但取消的下載資源我們還能繼續下載(恢復數據以供以后使用)。只有滿足以下條件時才能恢復下載: 1、請求資源后,資源並未發生變化 2、該任務是一個HTTP或HTTPS GET請求 3、服務器在其響應中提供ETag或Last-Modified標頭(或兩者都有) 4、服務器支持字節范圍請求 5、系統為響應磁盤空間壓力而未刪除臨時文件 * Cancel the download (and calls the superclass -cancel). If * conditions will allow for resuming the download in the future, the * callback will be called with an opaque data blob, which may be used * with -downloadTaskWithResumeData: to attempt to resume the download. * If resume data cannot be created, the completion handler will be * called with nil resumeData. - (void)cancelByProducingResumeData:(void (^)(NSData * _Nullable resumeData))completionHandler;
其實在看了上面的API解釋之后,大家會發現有一個我們還沒說,那就是NSURLSessionStreamTask,這個里面包含的內容比較多,並且和它包含了許多父類沒有的方法,在日常開發中我暫時是沒有遇到過這一塊的東西,但還是通過查找資料,把這一塊的API也相應的熟悉一下,方便以后我們查找使用:
@interface NSURLSessionStreamTask : NSURLSessionTask 異步地從流中讀取若干個字節,並在完成時調用處理程序。 讀取minBytes或最多maxBytes字節,並在會話委托隊列中調用數據或錯誤的完成處理程序。如果發生錯誤,任何未完成的讀取也將失敗,並且新的讀取請求將立即出錯。 * Read minBytes, or at most maxBytes bytes and invoke the completion * handler on the sessions delegate queue with the data or an error. * If an error occurs(發生), any outstanding(未完成) reads will also fail, and new * read requests will error out immediately. - (void)readDataOfMinLength:(NSUInteger)minBytes maxLength:(NSUInteger)maxBytes timeout:(NSTimeInterval)timeout completionHandler:(void (^) (NSData * _Nullable data, BOOL atEOF, NSError * _Nullable error))completionHandler; 將指定的數據異步寫入流,並在完成時調用處理程序 * Write the data completely to the underlying socket. If all the * bytes have not been written by the timeout, a timeout error will * occur. Note that invocation(調用) of the completion handler does not * guarantee (確保) that the remote side has received all the bytes, only * that they have been written to the kernel. - (void)writeData:(NSData *)data timeout:(NSTimeInterval)timeout completionHandler:(void (^) (NSError * _Nullable error))completionHandler; 獲取流 完成所有已排隊的讀取和寫入,然后調用URLSession:streamTask:didBecomeInputStream:outputStream:delegate消息。 收到該消息時,任務對象被視為已完成,並且不會再收到任何委托消息。 * -captureStreams completes any already enqueued(隊列) reads * and writes, and then invokes the * URLSession:streamTask:didBecomeInputStream:outputStream: delegate * message. When that message is received, the task object is * considered completed and will not receive any more delegate * messages. - (void)captureStreams; 排隊請求以關閉底層Socket的寫入結束。 所有未完成的IO將在Socket的寫入端關閉之前完成。 但是,服務器可能會繼續將字節寫回到客戶端,因此最佳做法是從服務器繼續讀取,直到你收到EOF。 * Enqueue a request to close the write end of the underlying socket. * All outstanding IO will complete before the write side of the * socket is closed. The server, however, may continue to write bytes * back to the client, so best practice is to continue reading from * the server until you receive EOF. - (void)closeWrite; 排隊請求以關閉底層Socket的讀取端。 所有未完成的IO將在讀取端關閉之前完成。 你可以繼續寫入服務器。 * Enqueue a request to close the read side of the underlying socket. * All outstanding IO will complete before the read side is closed. * You may continue writing to the server. - (void)closeRead; 開始加密握手。 握手在所有待處理IO完成后開始。 TLS認證回調被發送到會話-URLSession:task:didReceiveChallenge:completionHandler: * Begin encrypted handshake. The hanshake begins after all pending * IO has completed. TLS authentication callbacks are sent to the * session's -URLSession:task:didReceiveChallenge:completionHandler: - (void)startSecureConnection; 完成所有掛起的安全IO后,干凈地關閉安全連接。 * Cleanly close a secure connection after all pending secure IO has * completed. - (void)stopSecureConnection;
哇哇哇......看了看自己對API注釋的內容,發現還有差不多一半的內容沒有說,可這篇幅會很長呀.......
接下來按照API的內容我們要說的還有下面這個幾個點:
1、NSURLSessionTaskDelegate
2、NSURLSessionDataDelegate
3、NSURLSessionDownloadDelegate
4、NSURLSessionStreamDelegate
5、NSURLSessionTaskTransactionMetrics
6、NSURLSessionTaskMetrics
O__O "… 還是在起一篇總結吧,在接下來的文章中就會總結上面說的這六個點的API,以及我們的Demo,當然Demo還是得提前發出來的當你看到這篇文章的時候相信第二篇也已經是寫好了,只等發出...
Demo 連接點擊這里 (和以前的我們寫的關於AVFoundation)的Demo是在一起的,這部分的demo在NSURLSession文件夾下面,大家自己找找哈.
參考文章: