NSURLSession、NSURLSessionTask 使用翻译

原创 2016年05月30日 09:47:05
@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};





版权声明:本文为博主原创文章,如若转载请在明显位置注明出处。

相关文章推荐

iOS网络编程(六) NSURLSession详解

昨夜浏览Demo的时候,看到别人请求网络数据用的是NSURLSession,当时就在想这里什么,怎么没有用过,引起了我的好奇心,遂去百度-谷歌-官方文档一一查看,有了一定的了解,原来NSURLSess...

X-code 报错dyld: Symbol not found: _NSURLSessionTransferSizeUnknown

今天在iPhone4  6.0系统上运行项目 报错 dyld: Symbol not found: _NSURLSessionTransferSizeUnknown. 使用AFN2.0之前就已经知...
  • soindy
  • soindy
  • 2015年02月06日 15:25
  • 1954

NSURLSession的类型(断点续传,开始取消。后台运行)

/** 当前会话*/ @property (nonatomic,strong) NSURLSession *currentSession; /** 后台会话*/ @property (nonat...

WKWebView 的使用简介

WKWebView相对于UIWebView强大了很多,内存的消耗相对少了,所提供的接口也丰富了。 现在谈一谈WKWebView的基本使用 1. navigationDelegate - (void)w...
  • reylen
  • reylen
  • 2015年06月10日 09:31
  • 50254

iOS网络开发NSURLSession(二)DataTask+Demo

原创blog,转载请注明出处 blog.csdn.net/hello_hwc欢迎关注我的IOS-SDK讲解专栏 http://blog.csdn.net/column/details/huangw...

ios断点续传:NSURLSession和NSURLSessionDataTask实现

苹果提供的NSURLSessionDownloadTask虽然能实现断点续传,但是有些情况是无法处理的,比如程序强制退出或没有调用 cancelByProducingResumeData取消方法,这时...

iOS学习----------AFNetworking(5)NSURLSessionTask创建

上两篇中介绍了如何创建不同格式的request、序列化请求参数和处理响应数据、对数据进行格式化(JSON/XML)处理。接下来这一篇进行NSURLSessionTask创建进行详细分析(重点)。 ...
  • yziOS
  • yziOS
  • 2016年03月03日 22:03
  • 1390

NSURLSession学习笔记(二)Session Task

Session Task分为三种Data Task,Upload Task,Download Task。毫无疑问,Session Task是整个NSURLSession架构的核心目标。 下面写了...

NSURLSessionDownloadTask 出现 NSURLErrorDomain的解决方案

当你使用NSURLSessionDownloadTask下载资源时 可能会出现 NSURLErrorDomain类似的错误无法下载资源,以下是这种情况的解决方案:原因是: iOS9引入了新特性App ...

iOS网络通信-NSURLConnection

一、介绍     NSURLConnection通过提供的 URL request加载url的内容。NSURLConnection仅仅提供开始和取消网络请求,需要你在url 请求对象中自己进行配置。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:NSURLSession、NSURLSessionTask 使用翻译
举报原因:
原因补充:

(最多只允许输入30个字)