天天看點

NSURLSession、NSURLSessionTask 使用翻譯

@interface NSURLSessionTask : NSObject <NSCopying>

@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 */  //目前請求 可能與originalRequest 不同當伺服器重定向
@property (nullable, readonly, copy) NSURLResponse *response;         /* may be nil if no response has been received */ //響應

/* 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; //已經發送

/* number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
@property (readonly) int64_t countOfBytesExpectedToSend; //期望發送

/* 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; // 取消任務 如果調用 會使URLSession 調用 task:didCompleteWithError: 方法,錯誤資訊為  NSURLErrorDomain, NSURLErrorCancelled,,,在有的時候,取消也可能會被發送給一個暫停的任務

/*
 * 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;  // 錯誤資訊 與URLSession 的 task:didCompleteWithError: 錯誤資訊一緻 ,可能nil

/*
 * Suspending a task will prevent the NSURLSession from continuing to
 * load data.  There may still be delegate calls made on behalf of
 * this task (for instance, to report data received while suspending)
 * but no further transmissions will be made on behalf of the task
 * until -resume is sent.  The timeout timer associated with the task
 * will be disabled while a task is suspended. -suspend and -resume are
 * nestable.
 */
- (void)suspend;// 暫停  會防止 URLSession 接受資料, 任務的逾時計算着在暫停的時候也會停止計算。會一直等待到resume的資訊時才會繼續接受資訊。
- (void)resume; // 恢複任務

/*
 * Sets a scaling factor for the priority of the task. The scaling factor is a
 * value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
 * priority and 1.0 is considered the highest.
 *
 * The priority is a hint and not a hard requirement of task performance. The
 * priority of a task may be changed using this API at any time, but not all
 * protocols support this; in these cases, the last priority that took effect
 * will be used.
 *
 * If no priority is specified, the task will operate with the default priority
 * as defined by the constant NSURLSessionTaskPriorityDefault. Two additional
 * priority levels are provided: NSURLSessionTaskPriorityLow and
 * NSURLSessionTaskPriorityHigh, but use is not restricted to these.
 */
@property float priority NS_AVAILABLE(10_10, 8_0); // 任務的優先級 0 - 1.0 預設的三個優先級為 如下

@end

FOUNDATION_EXPORT const float NSURLSessionTaskPriorityDefault NS_AVAILABLE(10_10, 8_0);
FOUNDATION_EXPORT const float NSURLSessionTaskPriorityLow NS_AVAILABLE(10_10, 8_0);
FOUNDATION_EXPORT const float NSURLSessionTaskPriorityHigh NS_AVAILABLE(10_10, 8_0);







// 沒有特别功能,隻是為了區分 上傳 下載下傳
@interface NSURLSessionDataTask : NSURLSessionTask
@end
// 沒有特别功能,隻是為了在文法上差別 下載下傳 和普通熱舞
@interface NSURLSessionUploadTask : NSURLSessionDataTask
@end

// 下載下傳任務
@interface NSURLSessionDownloadTask : NSURLSessionTask

// 取消任務,同時調用父類的取消方法 在恢複的時候,block回調
- (void)cancelByProducingResumeData:(void (^)(NSData * __nullable resumeData))completionHandler;

@end


// 流任務
// 提供一個讀寫任務 針對TCP/IP 流
// 可能被NSURLSession 建立,也可能-URLSession:dataTask:didReceiveResponse: delegate message. 中建立
// 可以執行一個異步的讀寫,帶有完成回調,如果一個錯誤發生或者任務取消,所有的讀寫任務将會停止并且發出一個合适的錯誤資訊
// 同樣能夠用來對 NSUnputStream and NSOutputStream 執行個體類進行操作 從一個NSURLSessionTask 通過發送 captureStreams 到這個任務,在流被創造之前所有的讀寫任務都會完成,一旦流的劉希被發送給 session的代理的話,這個任務将視作完成,并且不會再接受任何資訊
@interface NSURLSessionStreamTask : NSURLSessionTask

- (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. */
// 完全的在socket的基礎之上進行寫資料,如果所有的位元組在逾時時間之内沒有被寫完的話,一個逾時的錯誤将會被發出,注意請求完成的回到并不會保證遠端端已經接受到了所有的額位元組,位元組僅僅是被寫到了核心之中
(void)writeData:(NSData *)data timeout:(NSTimeInterval)timeout completionHandler:(void (^) (NSError * __nullable error))completionHandler;

// 捕獲流資訊
// 會調用NSURLSession  streamTask:didBecomeInputStream:outputStream: 擷取資訊,如果資訊收到,則不會再接受任何代理點額資訊
(void)captureStreams;


// 關閉寫操作,關閉基于sock 的請求的寫操作,在socket寫的乙方所有的流輸入輸出都會被完成。然而伺服器可能會繼續寫位元組到用戶端,所有最好繼續讀資料直到你從伺服器接收到了所有的資料
(void)closeWrite;

(void)closeRead;

//session's -URLSession:task:didReceiveChallenge:completionHandler:
- (void)startSecureConnection; // 開始安全握手
(void)stopSecureConnection;


/*
 * Disposition options for various delegate messages
 */
// NSURLSession 的 驗證結果
// 代理資訊的處理
typedef NS_ENUM(NSInteger, NSURLSessionAuthChallengeDisposition) {
    // 使用者授權
    NSURLSessionAuthChallengeUseCredential = 0,                                       /* Use the specified credential, which may be nil */
    // 預設的處理 如:代理沒有回到,實作。不會再理睬證書參數
    NSURLSessionAuthChallengePerformDefaultHandling = 1,                              /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
    // 取消證書驗證 證書請求将會被取消,證書參數是nil
    NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2,                       /* The entire request will be canceled; the credential parameter is ignored. */
    // 拒絕,不會再理睬證書參數
    NSURLSessionAuthChallengeRejectProtectionSpace = 3,                               /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);










/*
 * The shared session uses the currently set global NSURLCache,
 * NSHTTPCookieStorage and NSURLCredentialStorage objects.
 */
/**
 *  共享的單例使用目前全局設定的 NSURLCache NSHTTPCookieStorage NSURLCredentialStorage
 */
+ (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.
 */
/**
 *  自定義的Session 可以通過建立一個新的session。發過你僅僅需要使用一個便利的正常配置的話,就沒有必要設定代理,代理會被retain(計數器加1)直到代理被發送了 URLSession:didBecomeInvalidWithError: 的消息
 */
// 建立一個session 沒有代理
+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
// 建立一個session 設定代理 設定執行的線程
+ (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.
 */
/**
 *  sessionDescription 允許開發者可以提供一個描述标簽給目前任務
 */
@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将會是代能夠繼續接收到回調,直到URLSession:didBecomeInvalidWithError:才會停止
    -finishTasksAndInvalidate and -invalidateAndCancel 對全局的單例session沒有影響
    當銷毀一個背景session的時候,如果以相同的名字在URLSession:didBecomeInvalidWithError: 之前 建立一個另外的背景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.
 */
/**
 *  這個方法和finshTasksAndInvalidate 的方法的響應是一樣的,但是他會調用session中所有任務的cancel方法。注意,任務的取消取決于任務的狀态,并且一些任務可能在接收到 cancel 方法的時候已經完成了
 */
- (void)invalidateAndCancel;


//清空所有的cookies cache credential stores(證書存儲),移除磁盤檔案,發送 -flushWithCompletionHandler:。在代理隊列中調用completionHandler
- (void)resetWithCompletionHandler:(void (^)(void))completionHandler;    /* empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil. */
// 清空磁盤和網絡傳輸緩沖
- (void)flushWithCompletionHandler:(void (^)(void))completionHandler;    /* flush storage to disk and clear transient network caches.  Invokes completionHandler() on the delegate queue if not nil. */


// 擷取 三種類型的 沒有完成的任務資料
- (void)getTasksWithCompletionHandler:(void (^)(NSArray<NSURLSessionDataTask *> *dataTasks, NSArray<NSURLSessionUploadTask *> *uploadTasks, NSArray<NSURLSessionDownloadTask *> *downloadTasks))completionHandler; /* invokes completionHandler with outstanding data, upload and download tasks. */

- (void)getAllTasksWithCompletionHandler:(void (^)(NSArray<__kindof NSURLSessionTask *> *tasks))completionHandler NS_AVAILABLE(10_11, 9_0); /* invokes completionHandler with all outstanding tasks. */


/*
 * NSURLSessionTask objects are always created in a suspended state and
 * must be sent the -resume message before they will execute.
 *  任務對象在建立的時候總是處于暫停狀态,在被執行之前會被調用 resume方法
 */


/* 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. */
/// 根據指定的request建立一個上傳任務,如果之前設定了request的 體 流 則是不予理睬的,當體流需要的額時候,會調用代理點的URLSession:task:needNewBodyStream:方法擷取
- (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 NS_AVAILABLE(10_11, 9_0);

/* Creates a bidirectional stream task with an NSNetService to identify the endpoint.
 * The NSNetService will be resolved before any IO completes.
 */
// 有執行的 NSNetService 對象建立一個雙向的流任務,并且 NSNetService對象在進出完成之前會被銷毀掉
- (NSURLSessionStreamTask *)streamTaskWithNetService:(NSNetService *)service NS_AVAILABLE(10_11, 9_0);










/*
 * NSURLSession convenience routines deliver results to
 * a completion handler block.  These convenience routines
 * are not available to NSURLSessions that are configured
 * as background sessions.
 *
 * Task objects are always created in a suspended state and
 * must be sent the -resume message before they will execute.
 */
/**
 *  NSURLSession 發送一個完成的結果回到(block)但是對于建立在背景的session不可用
 */
@interface NSURLSession (NSURLSessionAsynchronousConvenience)
/*
 * data task convenience methods.  These methods create tasks that
 * bypass the normal delegate calls for response and data delivery,
 * and provide a simple cancelable asynchronous interface to receiving
 * data.  Errors will be returned in the NSURLErrorDomain,
 * see <Foundation/NSURLError.h>.  The delegate, if any, will still be
 * called for authentication challenges.
 */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
 * upload convenience method.
 */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(nullable NSData *)bodyData completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

/*
 * 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.
 */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL * __nullable location, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;

@end









/*
 * Configuration options for an NSURLSession.  When a session is
 * created, a copy of the configuration object is made - you cannot
 * modify the configuration of a session after it has been created.
 *
 * The shared session uses the global singleton credential, cache
 * and cookie storage objects.
 *
 * An ephemeral session has no persistent disk storage for cookies,
 * cache or credentials.
 *
 * A background session can be used to perform networking operations
 * on behalf of a suspended application, within certain constraints.
 */
/**
 *  為NSURLSession的配置選項,當一個任務被建立的時候,會拷貝一份配置資訊,當一個session被建立之後,就不能在進行修改了
 *  共享的session 使用 全局的單例證書,緩存,和cookie存儲對象
 *  一個暫時的session 不會擁有以磁盤存儲cookies 緩存 和 證書的功能
 *  一個背景session可以用來在制定的限制之内執行一個暫停的應用的網絡請求
 *
 */
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interface NSURLSessionConfiguration : NSObject <NSCopying>

+ (NSURLSessionConfiguration *)defaultSessionConfiguration;
+ (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
+ (NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);

/* identifier for the background session configuration */
// 背景任務的ID表示
@property (nullable, readonly, copy) NSString *identifier;

/* default cache policy for requests */
// 請求的緩沖協定
@property NSURLRequestCachePolicy requestCachePolicy;

/* default timeout for requests.  This will cause a timeout if no data is transmitted for the given timeout value, and is reset whenever data is transmitted. */
// 預設的請求逾時時間,在指定的傳輸逾時時間之内,當沒有資料傳輸的時候 将會造成一個逾時的動作,并且在再次傳輸的時候,将會被從新設定
@property NSTimeInterval timeoutIntervalForRequest;

/* default timeout for requests.  This will cause a timeout if a resource is not able to be retrieved within a given timeout. */
// 預設的逾時時間。在指定逾時時間之内,如果不能重新擷取到資訊将會造成逾時的動作
@property NSTimeInterval timeoutIntervalForResource;

/* type of service for requests. */
@property NSURLRequestNetworkServiceType networkServiceType;

/* allow request to route over cellular. */
// 允許使用蜂窩資料
@property BOOL allowsCellularAccess;

/* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
// 是否允許背景任務是否允許系統自動做出決定和安排
@property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(10_10, 7_0);

//allowsCellularAccess 和 discretionary 被用于節省通過蜂窩網絡連接配接的帶寬。對于背景傳輸的情況,推薦大家使用 discretionary 這個屬性,而不是 allowsCellularAccess,因為前者會把 WiFi 和電源的可用性考慮在内。

// 魏總您好:
//     因個人原因,需請假一段時間,請假時間為 五月二十三号 至 五月二十七号,共計五天。請準許。

    // 申請人:王鐵山
    // 申請時間:2015-05-20

/* The identifier of the shared data container into which files in background sessions should be downloaded.
 * App extensions wishing to use background sessions *must* set this property to a valid container identifier, or
 * all transfers in that session will fail with NSURLErrorBackgroundSessionRequiresSharedContainer.
 */
/**
 *  背景任務将要下載下傳的資料容器的檔案,app擴充希望在使用背景session的時候必須設定這個屬性一個可用的容器身份,否則所有的在這個session中的傳輸都會失敗,錯誤參數為NSURLErrorBackgroundSessionRequiresSharedContainer
 [所有的傳輸将會在指定的檔案内建立]
 */
@property (nullable, copy) NSString *sharedContainerIdentifier NS_AVAILABLE(10_10, 8_0);

/*
 * Allows the app to be resumed or launched in the background when tasks in background sessions complete
 * or when auth is required. This only applies to configurations created with +backgroundSessionConfigurationWithIdentifier:
 * and the default value is YES.
 */
// 當任務在 background sessions 的類型上完成之後或要求授權的時候,是否允許app開始或恢複發送事件
// 這個僅僅應用在 以+backgroundSessionConfigurationWithIdentifier: 建立的對象之中。預設YES
// session是否發送開始事件通知,
@property BOOL sessionSendsLaunchEvents NS_AVAILABLE(NA, 7_0);

/* The proxy dictionary, as described by <CFNetwork/CFHTTPStream.h> */
@property (nullable, copy) NSDictionary *connectionProxyDictionary;

/* The minimum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
// 最低的SSL協定版本
@property SSLProtocol TLSMinimumSupportedProtocol;

/* The maximum allowable versions of the TLS protocol, from <Security/SecureTransport.h> */
// 最高的SSL協定版本
@property SSLProtocol TLSMaximumSupportedProtocol;

/* Allow the use of HTTP pipelining */
// 是否允許使用 HTTP 傳輸
@property BOOL HTTPShouldUsePipelining;

/* Allow the session to set cookies on requests */
// 是否允許HTTP設定cookies
@property BOOL HTTPShouldSetCookies;

/* Policy for accepting cookies.  This overrides the policy otherwise specified by the cookie storage. */
// HTTP cookie 協定
/**
 *  三個
 NSHTTPCookieAcceptPolicyAlways,
 NSHTTPCookieAcceptPolicyNever,
 NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain
 */
@property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy;

/* Specifies additional headers which will be set on outgoing requests.
 Note that these headers are added to the request only if not already present. */
// 指定的一些另外的頭資料,将會被設定在輸出請求上,【注意】 設定的頭将會在request還沒有發起的時候添加
@property (nullable, copy) NSDictionary *HTTPAdditionalHeaders;

/* The maximum number of simultanous persistent connections per host */
// 設定每個主機能夠同時連接配接的最大數量
@property NSInteger HTTPMaximumConnectionsPerHost;

/* The cookie storage object to use, or nil to indicate that no cookies should be handled */
// 将要使用的 coolie存儲對象,如果為nil表示沒有cookies将會被處理
@property (nullable, retain) NSHTTPCookieStorage *HTTPCookieStorage;

/* The credential storage object, or nil to indicate that no credential storage is to be used */
// 證書存儲
@property (nullable, retain) NSURLCredentialStorage *URLCredentialStorage;

/* The URL resource cache, or nil to indicate that no caching is to be performed */
@property (nullable, retain) NSURLCache *URLCache;

/* Enable extended background idle mode for any tcp sockets created.    Enabling this mode asks the system to keep the socket open
 *  and delay reclaiming it when the process moves to the background (see https://developer.apple.com/library/ios/technotes/tn2277/_index.html)
 */
// 使系統保持socket打開狀态,并且當進入背景模式的時候,延期清空
@property BOOL shouldUseExtendedBackgroundIdleMode NS_AVAILABLE(10_11, 9_0);

/* An optional array of Class objects which subclass NSURLProtocol.
 The Class will be sent +canInitWithRequest: when determining if
 an instance of the class can be used for a given URL scheme.
 You should not use +[NSURLProtocol registerClass:], as that
 method will register your class with the default session rather
 than with an instance of NSURLSession.
 Custom NSURLProtocol subclasses are not available to background
 sessions.
 */
// 一個用來存放NSURLProtocol子類的數組,數組中的類将會被發送 +canInitWithRequest: 用來确定是否這個類能夠用做一個給定給的schme。你不能使用 +[NSURLProtocol registerClass:],因為這個方法會用預設的session注冊你的類。而不會使用一個NSURLSession的執行個體對象。
// 自定義的NSURLProtocol的子類對于背景session不可用
@property (nullable, copy) NSArray<Class> *protocolClasses;

@end




typedef NS_ENUM(NSInteger, NSURLSessionResponseDisposition) {
    NSURLSessionResponseCancel = 0,                                      /* Cancel the load, this is the same as -[task cancel] */ // 調用task的cancel方法
    NSURLSessionResponseAllow = 1,                                       /* Allow the load to continue */
    NSURLSessionResponseBecomeDownload = 2,                              /* Turn this request into a download */
    NSURLSessionResponseBecomeStream NS_ENUM_AVAILABLE(10_11, 9_0) = 3,  /* Turn this task into a stream task */
} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);


typedef NS_ENUM(NSUInteger, NSURLRequestNetworkServiceType)
{
    NSURLNetworkServiceTypeDefault = 0,	// Standard internet traffic 預設傳輸方式
    NSURLNetworkServiceTypeVoIP = 1,	// Voice over IP control traffic
    NSURLNetworkServiceTypeVideo = 2,	// Video traffic    // 視訊傳輸
    NSURLNetworkServiceTypeBackground = 3, // Background traffic    // 背景模式
    NSURLNetworkServiceTypeVoice = 4	   // Voice data    // 音頻
};
typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy)
{
    //預設的緩存協定
    NSURLRequestUseProtocolCachePolicy = 0,
    //無論有無本地緩存資料 都進行從新請求
    NSURLRequestReloadIgnoringLocalCacheData = 1,
    //忽略本地和遠端的緩存資料 未實作的政策
    NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4,
    //無論有無緩存資料 都進行從新請求
    NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
    //先檢查緩存 如果沒有緩存再進行請求
    NSURLRequestReturnCacheDataElseLoad = 2,
    //類似離線模式,隻讀緩存 無論有無緩存都不進行請求
    NSURLRequestReturnCacheDataDontLoad = 3,
    //未實作的政策
    NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};








@protocol NSURLSessionDelegate <NSObject>
@optional

/* The last message a session receives.  A session will only become
 * invalid because of a systemic error or when it has been
 * explicitly invalidated, in which case the error parameter will be nil.
 */
// 當系統錯誤或者已經被銷毀的時候,error 為nil
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error;

/* If implemented, when a connection level authentication challenge
 * has occurred, this delegate will be given the opportunity to
 * provide authentication credentials to the underlying
 * connection. Some types of authentication will apply to more than
 * one request on a given connection to a server (SSL Server Trust
 * challenges).  If this delegate message is not implemented, the
 * behavior will be to use the default handling, which may involve user
 * interaction.
 */
// 如果代理方法沒有實作,NSURLAuthenticationChallenge 設定為default,并且可能請求使用者互動
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler;

/* If an application has received an
 * -application:handleEventsForBackgroundURLSession:completionHandler:
 * message, the session delegate will receive this message to indicate
 * that all messages previously enqueued for this session have been
 * delivered.  At this time it is safe to invoke the previously stored
 * completion handler, or to begin any internal updates that will
 * result in invoking the completion handler.
 */
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session NS_AVAILABLE_IOS(7_0);



/*
 * Messages related to the operation of a specific task.
 */
@protocol NSURLSessionTaskDelegate <NSURLSessionDelegate>
@optional

/* An HTTP request is attempting to perform a redirection to a different
 * URL. You must invoke the completion routine to allow the
 * redirection, allow the redirection with a modified request, or
 * pass nil to the completionHandler to cause the body of the redirection
 * response to be delivered as the payload of this request. The default
 * is to follow redirections.
 *
 * For tasks in background sessions, redirections will always be followed and this method will not be called.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler;

/* The task has received a request specific authentication challenge.
 * If this delegate is not implemented, the session specific authentication challenge
 * will *NOT* be called 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 * __nullable credential))completionHandler;

/* Sent if a task requires a new, unopened body stream.  This may be
 * necessary when authentication has failed for any request that
 * involves a body stream.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
 needNewBodyStream:(void (^)(NSInputStream * __nullable bodyStream))completionHandler;

/* Sent periodically to notify the delegate of upload progress.  This
 * information is also 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 specific task.  Error may be
 * nil, which implies that no error occurred and this task is complete.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error;

@end




/*
 * Messages related to the operation of a specific task.
 */
@protocol NSURLSessionTaskDelegate <NSURLSessionDelegate>
@optional

/* An HTTP request is attempting to perform a redirection to a different
 * URL. You must invoke the completion routine to allow the
 * redirection, allow the redirection with a modified request, or
 * pass nil to the completionHandler to cause the body of the redirection
 * response to be delivered as the payload of this request. The default
 * is to follow redirections.
 *
 * For tasks in background sessions, redirections will always be followed and this method will not be called.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler;

/* The task has received a request specific authentication challenge.
 * If this delegate is not implemented, the session specific authentication challenge
 * will *NOT* be called 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 * __nullable credential))completionHandler;

/* Sent if a task requires a new, unopened body stream.  This may be
 * necessary when authentication has failed for any request that
 * involves a body stream.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
 needNewBodyStream:(void (^)(NSInputStream * __nullable bodyStream))completionHandler;

/* Sent periodically to notify the delegate of upload progress.  This
 * information is also 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 specific task.  Error may be
 * nil, which implies that no error occurred and this task is complete.
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error;

@end

/*
 * Messages related to the operation of a task that delivers data
 * directly to the delegate.
 */
@protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@optional
/* The task has received a response and no further messages will be
 * received until the completion block is called. The disposition
 * allows you to cancel 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 will not be called for background upload tasks (which cannot be converted to download tasks).
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;

/* Notification that a data task has become a download task.  No
 * future messages will be sent to the data task.
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask;

/*
 * Notification that a data task has become a bidirectional stream
 * task.  No future messages will be sent to the data task.  The newly
 * created streamTask will carry the original request and response as
 * properties.
 *
 * For requests that were pipelined, the stream object will only allow
 * reading, and the object will immediately issue a
 * -URLSession:writeClosedForStream:.  Pipelining can be disabled for
 * all requests in a session, or by the NSURLRequest
 * HTTPShouldUsePipelining property.
 *
 * The underlying connection is no longer considered part of the HTTP
 * connection cache and won't count against the total number of
 * connections per host.
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didBecomeStreamTask:(NSURLSessionStreamTask *)streamTask;

/* Sent when data is available for the delegate to consume.  It is
 * assumed that the delegate will retain and not copy the data.  As
 * the data may be discontiguous, you should use
 * [NSData enumerateByteRangesUsingBlock:] to access it.
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data;

/* Invoke the completion routine with a valid NSCachedURLResponse to
 * allow the resulting data to be cached, or pass nil to prevent
 * caching. Note that there is no guarantee that caching will be
 * attempted for a given resource, and you should not rely on this
 * message to receive the resource data.
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
 willCacheResponse:(NSCachedURLResponse *)proposedResponse
 completionHandler:(void (^)(NSCachedURLResponse * __nullable cachedResponse))completionHandler;

@end

@end





NSString *userPasswordString = [NSString stringWithFormat:@"%@:%@", user, password];
NSData * userPasswordData = [userPasswordString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];
NSString *userAgentString = @"AppName/com.example.app (iPhone 5s; iOS 7.0.2; Scale/2.0)";

configuration.HTTPAdditionalHeaders = @{@"Accept": @"application/json",
                                        @"Accept-Language": @"en",
                                        @"Authorization": authString,
                                        @"User-Agent": userAgentString};





           

繼續閱讀