NSURLSession 文檔閱讀部分實踐

1//下載完成時調用 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location;

:URLSession:downloadTask:didFinishDownloadingToURL方法中,location只是一個磁盤上該文件的臨時 URL,只是一個臨時文件,需要自己使用NSFileManager將文件寫到應用的目錄下(一般來說這種可以重複獲得的內容應該放到cache目錄下),因爲當你從這個委託方法返回時,該文件將從臨時存儲中刪除。

2、在appDelegate中實現handleEventsForBackgroundURLSession,要注意的是,需要在handleEventsForBackgroundURLSession中必須重新建立一個後臺 session 的參照(可以用之前dispatch_once創建的對象),否則 NSURLSessionDownloadDelegate NSURLSessionDelegate 方法會因爲沒有 session delegate 設置而不會被調用。

然後保存completionHandler()

3handleEventsForBackgroundURLSession方法是在後臺下載的所有任務完成後纔會調用。如果當後臺傳輸完成時,如果應用程序已經被殺掉,iOS將會在後臺啓動該應用程序,下載相關的委託方法會在 application:didFinishLaunchingWithOptions:方法被調用之後被調用。

<以上三條內容來自網上>

4AFURLSessionManager 裏面的很多方法使用了NSURLDataTask的代理方法

5、NSURLSession is a replacement API for NSURLConnection 這是一個替換NSURLConnection的api

6、These are analogous(類似的) to NSURLConnection objects but provide for more control and a unified

 delegate model.

7Subclasses of NSURLSessionTask are used to syntactically(依照語法的)

 differentiate between data and file downloads.

8An NSURLSessionUploadTask differs from an NSURLSessionDataTask

 in how its instance is constructed.  Upload tasks are explicitly created

 by referencing a file or data object to upload, or by utilizing the

 -URLSession:task:needNewBodyStream: delegate message to supply an upload

 body.

9An NSURLSessionDownloadTask will directly write the response data to

 a temporary file.  When completed, the delegate is sent

 URLSession:downloadTask:didFinishDownloadingToURL: and given an opportunity 

 to move this file to a permanent location in its sandboxed container, or to

 otherwise read the file. If canceled, an NSURLSessionDownloadTask can

 produce a data blob() that can be used to resume a download at a later

 time.(如果被取消,這個task能產生一個數據圖案,重啓一個下載,也就是傳說中的斷點下載)

10 //設置內存緩存和磁盤緩存大小

  創建緩存

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:self.MemoryCapacity * 1024 * 1024 diskCapacity:self.diskCapacity * 1024 * 1024 diskPath:nil];

    [NSURLCache setSharedURLCache:URLCache];

  通過這個方法來設置緩存數據的關聯

 [self.imageCache setObject:image forKey:urlStr];

11、sharedSession

/*

 * The shared session uses the currently(目前的) set global NSURLCache,

 * NSHTTPCookieStorage and NSURLCredentialStorage objects.

 */

12session會話

13routines 常規,慣例

14

/*

 * 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.

 */

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

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

15/*

 * The sessionDescription property is available for the developer to

 * provide a descriptive(描述性的) label(標籤) for the session.

 */

@property (nullable, copy) NSString *sessionDescription;

16 * When invalidating a background session, it is not safe to create another background

 * session with the same identifier until URLSession:didBecomeInvalidWithError: has

 * been issued.

當對一個後臺會話失效時,在RLSession:didBecomeInvalidWithError發佈之前創建一個相同id的會話是不安全的。

17、- (void)flushWithCompletionHandler:(void (^)(void))completionHandler; 

flush沖洗

18/* 

 * NSURLSessionTask objects are always created in a suspended state and

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

 */

task創建處於一個掛起狀態,在他們執行前,必須給它發送resume信息

19、/* 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;

20/* 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;

如果這個下載不能被喚起,是不是 說明這個task已經完成。

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

(1)NSURLSession convenience routines deliver results to 

 a completion handler block.  These convenience routines

 are not available to NSURLSessions that are configured

as background sessions.

這些接口不適合用在配有後臺的NSURLSessions 

(2)these methods create tasks that bypass(繞開) the normal delegate calls for response and data delivery.


22/*

 * download task convenience methods.  When a download successfully

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

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

 * will be removed automatically.

 */

將會被自動移除

23、suspend a task will prevent the NSURLSEssion from continuing to load data.

24、An NSURLSessionDataTask does not provide any additional functionality over an NSURLSessionTask and its presence is merely(僅僅只不過) to provide lexical(詞彙上) differentiaion from download and upload tasks.

25、NSURLSession 會話,NSURLSessionTask會話任務。

26、/* 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;

取消之後會產生重啓開始數據,供下次使用

27/*

 * An NSURLSessionStreamTask provides an interface to perform reads

 * and writes to a TCP/IP stream created via NSURLSession.  This task

 * may be explicitly(明確的) created from an NSURLSession, or created as a

 * result of the appropriate disposition(處置,部署) response to a

 * -URLSession:dataTask:didReceiveResponse: delegate message.

 * 

 * NSURLSessionStreamTask can be used to perform asynchronous reads

 * and writes.  Reads and writes are enquened(排隊) and executed(已執行的,已經生效的) serially(連續的),

 * with the completion handler being invoked on the sessions delegate

 * queuee.  If an error occurs, or the task is canceled, all

 * outstanding read and write calls will have their completion

 * handlers invoked with an appropriate error.

 *

 * It is also possible to create NSInputStream and NSOutputStream

 * instances from an NSURLSessionTask by sending

 * -captureStreams to the task.  All outstanding read and writess are

 * completed before the streams are created.  Once the streams are

 * delivered to the session delegate, the task is considered complete

 * and will receive no more messsages.  These streams are

 * disassociated from the underlying session.

 */

28[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[[NSProcessInfo processInfo] globallyUniqueString]];

id 每次加載都要不一樣,這個非常重要

參考文章:

http://192.168.2.56:8883/docs/show/124

https://github.com/yyhinbeijing/XZDownloadTask

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章