写在前面:
先把自己整理的内容放出来,后续补充示例
1 类库功能简介
1.1 AFNetworking 的大体思路
1.1.1 NSURLConnection NSOperation daozhe
NSURLConnection
是 Foundation URL 加载系统的基石。一个 NSURLConnection
异步地加载一个 NSURLRequest
对象,调用 delegate 的 NSURLResponse
/ NSHTTPURLResponse
方法,其 NSData
被发送到服务器或从服务器读取;delegate 还可用来处理 NSURLAuthenticationChallenge
、重定向响应、或是决定 NSCachedURLResponse
如何存储在共享的 NSURLCache
上。
NSOperation
是抽象类,模拟单个计算单元,有状态、优先级、依赖等功能,可以取消。
AFNetworking的第一个重大突破就是将两者结合。AFURLConnectionOperation
作为 NSOperation
的子类,遵循NSURLConnectionDelegate
的方法,可以从头到尾监视请求的状态,并储存请求、响应、响应数据等中间状态。
1.1.2 Blocks
iOS 4 引入的 block 和 GrandCentral Dispatch 从根本上改善了应用程序的开发过程。相比于在应用中用 delegate 乱七八糟地实现逻辑,开发者们可以用block 将相关的功能放在一起。GCD能够轻易来回调度工作,不用面对乱七八糟的线程、调用和操作队列。
更重要的是,对于每个request operation,可以通过 block 自定义 NSURLConnectionDelegate
的方法(比如,通过setWillSendRequestForAuthenticationChallengeBlock:
可以覆盖默认的connection:willSendRequestForAuthenticationChallenge:
方法)。
现在,我们可以创建 AFURLConnectionOperation
并把它安排进 NSOperationQueue
,通过设置 NSOperation
的新属性completionBlock
,指定操作完成时如何处理response 和response data(或是请求过程中遇到的错误)。
1.1.3 序列化 & 验证
更深入一些,requestoperation 操作也可以负责验证HTTP 状态码和服务器响应的内容类型,比如,对于application/json
MIME 类型的响应,可以将 NSData 序列化为JSON 对象。
从服务器加载 JSON、XML、property list 或者图像可以抽象并类比成潜在的文件加载操作,这样开发者可以将这个过程想象成一个promise 而不是异步网络连接。
1.2 AFN 1.0版本
1.2.1 AFN1.0架构设计原理
AFN 的基础部分是 AFURLConnectionOperation,一个 NSOperation subclass,实现了 基于NSURLConnection 相关的delegate blocks,网络部分是由 NSURLConnection 完成,然后利用 NSOperation 的 state (isReady→isExecuting→isFinished) 变化来进行网络控制。网络请求是在一个指定的线程(networkRequestThread)完成。
AFURLConnectionOperation是一个很纯粹的网络请求 operation,可以对他进行 start/cancel/pause/resume 操作,可以获取对应的 NSURLRequest 和 NSURLResponse 数据。支持 NSInputStream/NSOutputStream,提供了 uploadPress 和downloadProgress 以方便其他使用。
AFHTTPRequestOperation是 AFURLConnectionOperation 的子类,针对 HTTP HTTPS 协议做了一层封装,比如statusCode、Content-Type 等,添加了请求成功和失败的回调 block,提供了addAcceptableContentTypes: 以方便上层使用。
1.2.2 各个类功能说明
Ø AFURLConnectionOperation和它的子类继承NSOperation的,允许请求被取消,暂停/恢复和由NSOperationQueue进行管理。
Ø AFURLConnectionOperation也可以让你轻松得完成上传和下载,处理验证,监控上传和下载进度,控制的缓存。
Ø AFHTTPRequestOperation和它得子类可以基于http状态和 内容列下来区分是否成功请求了。
Ø AFNetworking可以将远程媒体数据类型(NSData)转化为可用的格式,比如如JSON,XML,图像和plist。
Ø AFHTTPClient提供了一个方便的网络交互接口,包括默认头,身份验证,是否连接到网络,批量处理操作,查询字符串参数序列化,已经多种表单请求的UIImageView AFNetworking增加了一个方便的方法来异步加载图像。
1.3 AFN 2.0版本
1.3.1 动机
· 兼容NSURLSession - NSURLSession
是 iOS 7 新引入的用于替代 NSURLConnection
的类。NSURLConnection
并没有被弃用,今后一段时间应该也不会,但是 NSURLSession
是 Foundation中网络的未来,并且是一个美好的未来,因为它改进了之前的很多缺点。(参考WWDC 2013 Session 705 “What’s New in Foundation Networking”,一个很好的概述)。起初有人推测,NSURLSession
的出现将使AFNetworking 不再有用。但实际上,虽然它们有一些重叠,AFNetworking还是可以提供更高层次的抽象。AFNetworking2.0 不仅做到了这一点,还借助并扩展 NSURLSession
来铺平道路上的坑洼,并最大程度扩展了它的实用性。
· 模块化 -对于AFNetworking 的主要批评之一是笨重。虽然它的构架使在类的层面上是模块化的,但它的包装并不允许选择独立的一些功能。随着时间的推移,AFHTTPClient
尤其变得不堪重负(其任务包括创建请求、序列化query string 参数、确定响应解析行为、生成和管理operation、监视网络可达性)。 在AFNetworking 2.0 中,你可以挑选并通过 CocoaPods subspecs 选择你所需要的组件。
1.3.2 主要组件
1.3.2.1NSURLConnection
组件 (iOS 6 & 7)
- AFURLConnectionOperation - NSOperation 的子类,负责管理 NSURLConnection 并且实现其 delegate 方法。
- AFHTTPRequestOperation - AFURLConnectionOperation 的子类,用于生成 HTTP 请求,可以区别可接受的和不可接受的状态码及内容类型。2.0 版本中的最大区别是,你可以直接使用这个类,而不用继承它,原因可以在“序列化”一节中找到。
- AFHTTPRequestOperationManager - 包装常见 HTTP web 服务操作的类,通过 AFHTTPRequestOperation 由NSURLConnection 支持。
1.3.2.2NSURLSession
组件 (iOS 7)
AFURLSessionManager
- 创建、管理基于NSURLSessionConfiguration
对象的NSURLSession
对象的类,也可以管理 session 的数据、下载/上传任务,实现 session 和其相关联的任务的 delegate 方法。因为NSURLSession
API 设计中奇怪的空缺,任何和NSURLSession
相关的代码都可以用AFURLSessionManager
改善。AFHTTPSessionManager
-AFURLSessionManager
的子类,包装常见的 HTTP web 服务操作,通过AFURLSessionManager
由NSURLSession
支持。
1.3.3 综述
总的来说:为了支持新的 NSURLSession API 以及旧的未弃用且还有用的NSURLConnection,AFNetworking 2.0 的核心组件分成了 request operation 和 session 任务。AFHTTPRequestOperationManager 和 AFHTTPSessionManager 提供类似的功能,在需要的时候(比如在 iOS 6 和 7 之间转换),它们的接口可以相对容易的互换。
1.3.4 功能特性
1.3.4.1 序列化
AFNetworking2.0 新构架的突破之一是使用序列化来创建请求、解析响应。可以通过序列化的灵活设计将更多业务逻辑转移到网络层,并更容易定制之前内置的默认行为。
· <AFURLRequestSerializer>
-符合这个协议的对象用于处理请求,它将请求参数转换为 query string 或是 entity body 的形式,并设置必要的 header。那些不喜欢 AFHTTPClient
使用query string 编码参数的家伙,你们一定喜欢这个。
· <AFURLResponseSerializer>
-符合这个协议的对象用于验证、序列化响应及相关数据,转换为有用的形式,比如 JSON 对象、图像、甚至基于 Mantle 的模型对象。相比没完没了地继承 AFHTTPClient
,现在AFHTTPRequestOperation
有一个 responseSerializer
属性,用于设置合适的handler。同样的,再也没有没用的受NSURLProtocol
启发的 request operation 类注册,取而代之的还是很棒的 responseSerializer
属性。
1.3.4.2 安全性
AFNetworking现在带有内置的 SSL pinning 支持,这对于处理敏感信息的应用是十分重要的。
AFSecurityPolicy
- 评估服务器对安全连接针对指定的固定证书或公共密钥的信任。将你的服务器证书添加到 app bundle,以帮助防止 中间人攻击。
1.3.4.3 可达性
从 AFHTTPClient
解藕的另一个功能是网络可达性。现在你可以直接使用它,或者使用 AFHTTPRequestOperationManager
/AFHTTPSessionManager
的属性。
l AFNetworkReachabilityManager- 这个类监控当前网络的可达性,提供回调block 和notificaiton,在可达性变化时调用。
1.3.4.4 实时性
l AFEventSource - EventSourceDOM API 的 Objective-C 实现。建立一个到某主机的持久 HTTP 连接,可以将事件传输到事件源并派发到听众。传输到事件源的消息的格式为 JSON Patch 文件,并被翻译成AFJSONPatchOperation 对象的数组。可以将这些patch operation 应用到之前从服务器获取的持久性数据集。
代码语言:javascript复制NSURL *URL = [NSURLURLWithString:@"http://example.com"]; AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL];
代码语言:javascript复制[manager GET:@"/resources"parameters:nilsuccess:^(NSURLSessionDataTask *task, id responseObject) {
代码语言:javascript复制[resources addObjectsFromArray:responseObject[@"resources"]];
代码语言:javascript复制[manager SUBSCRIBE:@"/resources"usingBlock:^(NSArray *operations, NSError *error) {
代码语言:javascript复制for (AFJSONPatchOperation *operation in operations) {
代码语言:javascript复制 switch (operation.type) {
代码语言:javascript复制 case AFJSONAddOperationType:
代码语言:javascript复制 [resources addObject:operation.value];
代码语言:javascript复制 break;
代码语言:javascript复制 default:
代码语言:javascript复制 break;
代码语言:javascript复制 }
代码语言:javascript复制}
代码语言:javascript复制} error:nil];
代码语言:javascript复制} failure:nil];
1.3.4.5 UIKit 扩展
之前AFNetworking 中的所有UIKit category 都被保留并增强,还增加了一些新的category。
AFNetworkActivityIndicatorManager
:在请求操作开始、停止加载时,自动开始、停止状态栏上的网络活动指示图标。UIImageView AFNetworking
:增加了imageResponseSerializer
属性,可以轻松地让远程加载到 image view上的图像自动调整大小或应用滤镜。 比如,AFCoreImageSerializer
可以在 response 的图像显示之前应用 Core Image filter。UIButton AFNetworking
(新):与UIImageView AFNetworking
类似,从远程资源加载image
和backgroundImage
。UIActivityIndicatorView AFNetworking
(新):根据指定的请求操作和会话任务的状态自动开始、停止UIActivityIndicatorView
。UIProgressView AFNetworking
(新):自动跟踪某个请求或会话任务的上传/下载进度。UIWebView AFNetworking
(新): 为加载 URL 请求提供了更强大的API, 支持进度回调和内容转换。
2 AFURLConnectionOperation类
@interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>
2.1 成员属性
2.1.1 NSRunLoopCommonModes集合属性
///-------------------------------
/// @name Accessing Run Loop Modes
///-------------------------------
/**
The run loop modesin which the operation will run on the network thread. By default, this is asingle-member set containing `NSRunLoopCommonModes`.
*/
@property (nonatomic, strong) NSSet *runLoopModes;
2.1.2 NSURLRequest请求对象属性
///-----------------------------------------
/// @name Getting URL Connection Information
///-----------------------------------------
/**
The request usedby the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLRequest *request;
2.1.3 NSURLResponse响应对象属性
/**
The last responsereceived by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSURLResponse*response;
2.1.4 请求生命周期过程中产生的错误信息
/**
The error, if any,that occurred in the lifecycle of the request.
*/
@property (readonly, nonatomic, strong) NSError *error;
///----------------------------
/// @name Getting Response Data
///----------------------------
2.1.5 响应数据属性
/**
The data receivedduring the request.
*/
@property (readonly, nonatomic, strong) NSData *responseData;
2.1.6 响应数据字符串
/**
The stringrepresentation of the response data.
*/
@property (readonly, nonatomic, copy) NSString *responseString;
2.1.7 已编码的响应数据字符串
/**
The stringencoding of the response.
If the responsedoes not specify a valid string encoding, `responseStringEncoding` will return`NSUTF8StringEncoding`.
*/
@property (readonly, nonatomic, assign) NSStringEncodingresponseStringEncoding;
2.1.8 是否使用存储的共享凭证
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether the URLconnection should consult the credential storage for authenticating theconnection. `YES` by default.
This is the valuethat is returned in the `NSURLConnectionDelegate` method`-connectionShouldUseCredentialStorage:`.
*/
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
2.1.9 NSURLCredential凭证
/**
The credentialused for authentication challenges in`-connection:didReceiveAuthenticationChallenge:`.
This will beoverridden by any shared credentials that exist for the username or password ofthe request URL, if present.
*/
@property (nonatomic, strong) NSURLCredential*credential;
2.1.10 AFSecurityPolicy安全策略属性
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The securitypolicy used to evaluate server trust for secure connections.
*/
@property (nonatomic, strong) AFSecurityPolicy*securityPolicy;
2.1.11 待发送数据的NSInputStream对象属性
///------------------------
/// @name Accessing Streams
///------------------------
/**
The input streamused to read data to be sent during the request.
This property actsas a proxy to the `HTTPBodyStream` property of `request`.
*/
@property (nonatomic, strong) NSInputStream*inputStream;
2.1.12 接收数据的NSOutputStream对象属性
/**
The output streamthat is used to write data received until the request is finished.
By default, datais accumulated into a buffer that is stored into `responseData` upon completionof the request, with the intermediary `outputStream` property set to `nil`.When `outputStream` is set, the data will not be accumulated into an internalbuffer, and as a result, the `responseData` property of the completed requestwill be `nil`. The output stream will be scheduled in the network threadrunloop upon being set.
*/
@property (nonatomic, strong) NSOutputStream*outputStream;
2.1.13 请求完成后的处理队列属性
///---------------------------------
/// @name Managing Callback Queues
///---------------------------------
/**
The dispatch queuefor `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong) dispatch_queue_tcompletionQueue;
2.1.14 请求完成后的处理Group属性
/**
The dispatch groupfor `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong) dispatch_group_tcompletionGroup;
2.1.15 UserInfo字典属性
///---------------------------------------------
/// @name Managing Request Operation Information
///---------------------------------------------
/**
The user infodictionary for the receiver.
*/
@property (nonatomic, strong) NSDictionary *userInfo;
2.2 成员方法
2.2.1 初始化方法initWithRequest
///------------------------------------------------------
/// @name Initializing an AFURLConnectionOperation Object
///------------------------------------------------------
/**
Initializes andreturns a newly allocated operation object with a url connection configuredwith the specified url request.
This is thedesignated initializer.
@param urlRequest Therequest object to be used by the operation connection.
*/
- (instancetype)initWithRequest:(NSURLRequest *)urlRequest;
2.2.2 暂停方法
///----------------------------------
/// @name Pausing / Resuming Requests
///----------------------------------
/**
Pauses theexecution of the request operation.
A paused operationreturns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, itwill remain in an `NSOperationQueue` until it is either cancelled or resumed.Pausing a finished, cancelled, or paused operation has no effect.
*/
- (void)pause;
2.2.3 是否已暂停方法
/**
Whether therequest operation is currently paused.
@return `YES` if theoperation is currently paused, otherwise `NO`.
*/
- (BOOL)isPaused;
2.2.4 恢复请求方法
/**
Resumes theexecution of the paused request operation.
Pause/Resumebehavior varies depending on the underlying implementation for the operationclass. In its base implementation, resuming a paused requests restarts theoriginal request. However, since HTTP defines a specification for how torequest a specific content range, `AFHTTPRequestOperation` will resumedownloading the request from where it left off, instead of restarting theoriginal request.
*/
- (void)resume;
2.2.5 设置是否可以在后台执行的方法
///----------------------------------------------
/// @name Configuring Backgrounding Task Behavior
///----------------------------------------------
/**
Specifies that theoperation should continue execution after the app has entered the background,and the expiration handler for that background task.
@param handler Ahandler to be called shortly before the application’s remaining background timereaches 0. The handler is wrapped in a block that cancels the operation, andcleans up and marks the end of execution, unlike the `handler` parameter in`UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects thisto be done in the handler itself. The handler is called synchronously on themain thread, thus blocking the application’s suspension momentarily while theapplication is notified.
*/
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) &&!defined(AF_APP_EXTENSIONS)
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
#endif
2.2.6 设置上传进度跟踪block
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
Sets a callback tobe called when an undetermined number of bytes have been uploaded to theserver.
@param block A blockobject to be called when an undetermined number of bytes have been uploaded tothe server. This block has no return value and takes three arguments: thenumber of bytes written since the last time the upload progress block wascalled, the total bytes written, and the total bytes expected to be writtenduring the request, as initially determined by the length of the HTTP body.This block may be called multiple times, and will execute on the main thread.
*/
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long longtotalBytesWritten, long long totalBytesExpectedToWrite))block;
2.2.7 设置下载进度跟踪block
/**
Sets a callback tobe called when an undetermined number of bytes have been downloaded from theserver.
@param block A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes three arguments: thenumber of bytes read since the last time the download progress block wascalled, the total bytes read, and the total bytes expected to be read duringthe request, as initially determined by the expected content size of the`NSHTTPURLResponse` object. This block may be called multiple times, and willexecute on the main thread.
*/
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long longtotalBytesExpectedToRead))block;
2.2.8 发送验证请求前执行的block
///-------------------------------------------------
/// @name Setting NSURLConnection Delegate Callbacks
///-------------------------------------------------
/**
Sets a block to beexecuted when the connection will authenticate a challenge in order to downloadits request, as handled by the `NSURLConnectionDelegate` method`connection:willSendRequestForAuthenticationChallenge:`.
@param block A blockobject to be executed when the connection will authenticate a challenge inorder to download its request. The block has no return type and takes twoarguments: the URL connection object, and the challenge that must beauthenticated. This block must invoke one of the challenge-responder methods(NSURLAuthenticationChallengeSender protocol).
If`allowsInvalidSSLCertificate` is set to YES,`connection:willSendRequestForAuthenticationChallenge:` will attempt to havethe challenge sender use credentials with invalid SSL certificates.
*/
- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection*connection, NSURLAuthenticationChallenge *challenge))block;
2.2.9 设置URL重定向时执行的block
/**
Sets a block to beexecuted when the server redirects the request from one URL to another URL, orwhen the request URL changed by the `NSURLProtocol` subclass handling therequest in order to standardize its format, as handled by the`NSURLConnectionDataDelegate` method`connection:willSendRequest:redirectResponse:`.
@param block A blockobject to be executed when the request URL was changed. The block returns an`NSURLRequest` object, the URL request to redirect, and takes three arguments:the URL connection object, the the proposed redirected request, and the URLresponse that caused the redirect.
*/
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection*connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
2.2.10 设置缓存响应前执行的block
/**
Sets a block to beexecuted to modify the response a connection will cache, if any, as handled bythe `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
@param block A blockobject to be executed to determine what response a connection will cache, ifany. The block returns an `NSCachedURLResponse` object, the cached response tostore in memory or `nil` to prevent the response from being cached, and takestwo arguments: the URL connection object, and the cached response provided forthe request.
*/
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection*connection, NSCachedURLResponse *cachedResponse))block;
2.2.11 批量处理方法
///
/**
*/
(NSArray *)batchOfRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUIntegertotalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
3 AFHTTPRequestOperation类
3.1 成员属性
3.1.1 最后接收到的响应对象
///------------------------------------------------
/// @name Getting HTTP URL Connection Information
///------------------------------------------------
/**
The last HTTPresponse received by the operation's connection.
*/
@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
3.1.2 AFHTTPResponseSerializer响应序列化器对象
/**
Responses sentfrom the server in data tasks created with `dataTaskWithRequest:success:failure:`and run using the `GET` / `POST` / et al. convenience methods are automaticallyvalidated and serialized by the response serializer. By default, this propertyis set to an AFHTTPResponse serializer, which uses the raw data as its responseobject. The serializer validates the status code to be in the `2XX` range,denoting success. If the response serializer generates an error in`-responseObjectForResponse:data:error:`, the `failure` callback of the sessiontask or request operation will be executed; otherwise, the `success` callbackwill be executed.
@warning`responseSerializer` must not be `nil`. Setting a response serializer willclear out any cached value
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
3.1.3 序列化处理后的响应数据对象
/**
An objectconstructed by the `responseSerializer` from the response and response data.Returns `nil` unless the operation `isFinished`, has a `response`, and has`responseData` with non-zero content length. If an error occurs during serialization,`nil` will be returned, and the `error` property will be populated with theserialization error.
*/
@property (readonly, nonatomic, strong) id responseObject;
3.2 成员方法
3.2.1 请求结束后执行的block
///-----------------------------------------------------------
/// @name Setting Completion Block Success / Failure Callbacks
///-----------------------------------------------------------
/**
Sets the`completionBlock` property with a block that executes either the specifiedsuccess or failure block, depending on the state of the request on completion.If `error` returns a value, which can be caused by an unacceptable status codeor content type, then `failure` is executed. Otherwise, `success` is executed.
This method shouldbe overridden in subclasses in order to specify the response object passed intothe success block.
@param success Theblock to be executed on the completion of a successful request. This block hasno return value and takes two arguments: the receiver operation and the objectconstructed from the response data of the request.
@param failure Theblock to be executed on the completion of an unsuccessful request. This blockhas no return value and takes two arguments: the receiver operation and theerror that occurred during the request.
*/
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, idresponseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4 AFHTTPRequestOperationManager类
4.1 成员属性
4.1.1 域名或者顶级目录URL
/**
The URL used tomonitor reachability, and construct requests from relative paths in methodslike `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al.convenience methods.
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
4.1.2 AFHTTPRequestSerializer请求序列化器
/**
Requests createdwith `requestWithMethod:URLString:parameters:` &`multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`are constructed with a set of default headers using a parameter serializationspecified by this property. By default, this is set to an instance of`AFHTTPRequestSerializer`, which serializes query string parameters for `GET`,`HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP messagebodies.
@warning`requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
4.1.3 AFHTTPResponseSerializer响应序列化器
/**
Responses sentfrom the server in data tasks created with`dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / etal. convenience methods are automatically validated and serialized by theresponse serializer. By default, this property is set to a JSON serializer,which serializes data from responses with a `application/json` MIME type, andfalls back to the raw data object. The serializer validates the status code tobe in the `2XX` range, denoting success. If the response serializer generatesan error in `-responseObjectForResponse:data:error:`, the `failure` callback ofthe session task or request operation will be executed; otherwise, the`success` callback will be executed.
@warning`responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
4.1.4 操作队列
/**
The operationqueue on which request operations are scheduled and run.
*/
@property (nonatomic, strong) NSOperationQueue*operationQueue;
4.1.5 设置是否需要存储凭证
///-------------------------------
/// @name Managing URL Credentials
///-------------------------------
/**
Whether requestoperations should consult the credential storage for authenticating theconnection. `YES` by default.
@see AFURLConnectionOperation-shouldUseCredentialStorage
*/
@property (nonatomic, assign) BOOLshouldUseCredentialStorage;
4.1.6 NSURLCredential凭证对象
/**
The credentialused by request operations for authentication challenges.
@seeAFURLConnectionOperation -credential
*/
@property (nonatomic, strong) NSURLCredential*credential;
4.1.7 AFSecurityPolicy安全策略对象
///-------------------------------
/// @name Managing Security Policy
///-------------------------------
/**
The securitypolicy used by created request operations to evaluate server trust for secureconnections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unlessotherwise specified.
*/
@property (nonatomic, strong) AFSecurityPolicy*securityPolicy;
4.1.8 网络监控对象
///------------------------------------
/// @name Managing Network Reachability
///------------------------------------
/**
The networkreachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager`by default.
*/
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
4.1.9 请求完成处理队列
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queuefor the `completionBlock` of request operations. If `NULL` (default), the mainqueue is used.
*/
@property (nonatomic, strong) dispatch_queue_tcompletionQueue;
4.1.10 请求完成处理Group
/**
The dispatch groupfor the `completionBlock` of request operations. If `NULL` (default), a privatedispatch group is used.
*/
@property (nonatomic, strong) dispatch_group_tcompletionGroup;
///---------------------------------------------
/// @name Creating and Initializing HTTP Clients
///---------------------------------------------
4.2 成员方法
4.2.1 单例方法
/**
Creates andreturns an `AFHTTPRequestOperationManager` object.
*/
(instancetype)manager;
4.2.2 初始化方法initWithBaseURL
/**
Initializes an`AFHTTPRequestOperationManager` object with the specified base URL.
This is thedesignated initializer.
@param url The baseURL for the HTTP client.
@return Thenewly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url;
4.2.3 创建AFHTTPRequestOperation对象方法
///---------------------------------------
/// @name Managing HTTP Request Operations
///---------------------------------------
/**
Creates an`AFHTTPRequestOperation`, and sets the response serializers to that of the HTTPclient.
@param request Therequest object to be loaded asynchronously during execution of the operation.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the created requestoperation and the object created from the response data of request.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes two arguments:, thecreated request operation and the `NSError` object describing the network orparsing error that occurred.
*/
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
///---------------------------
/// @name Making HTTP Requests
///---------------------------
4.2.4 创建一个Get请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `GET` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.5 创建一个Head请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `HEAD` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes a single arguments: the requestoperation.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.6 创建一个Post请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `POST` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, idresponseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.7 创建多个Post请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a multipart `POST` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param block A blockthat takes a single argument and appends data to the HTTP body. The blockargument is an object adopting the `AFMultipartFormData` protocol.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(AFHTTPRequestOperation *operation, idresponseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.8 创建一个Put请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `PUT` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.9 创建一个Patch请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `PATCH` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
4.2.10 创建一个Delete请求的AFHTTPRequestOperation对象
/**
Creates and runsan `AFHTTPRequestOperation` with a `DELETE` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the request operation finishes successfully.This block has no return value and takes two arguments: the request operation,and the response object created by the client response serializer.
@param failure Ablock object to be executed when the request operation finishes unsuccessfully,or that finishes successfully, but encountered an error while parsing theresponse data. This block has no return value and takes a two arguments: therequest operation and the error describing the network or parsing error thatoccurred.
@see-HTTPRequestOperationWithRequest:success:failure:
*/
- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
5 NSURLSession
5.1 URL Session的基本概念
NSURLSession是iOS7中新的网络接口,它与咱们熟悉的NSURLConnection是并列的。在程序在前台时,NSURLSession与NSURLConnection可以互为替代工作。注意,如果用户强制将程序关闭,NSURLSession会断掉。
NSURLSession提供的功能:
1.通过URL将数据下载到内存
2.通过URL将数据下载到文件系统
3.将数据上传到指定URL
4.在后台完成上述功能
5.1.1 三种工作模式
默认会话模式(default):工作模式类似于原来的NSURLConnection,使用的是基于磁盘缓存的持久化策略,使用用户keychain中保存的证书进行认证授权。
瞬时会话模式(ephemeral):该模式不使用磁盘保存任何数据。所有和会话相关的caches,证书,cookies等都被保存在RAM中,因此当程序使会话无效,这些缓存的数据就会被自动清空。
后台会话模式(background):该模式在后台完成上传和下载,在创建Configuration对象的时候需要提供一个NSString类型的ID用于标识完成工作的后台会话。
5.1.2 NSURLSession支持的三种任务
NSURLSession类支持三种类型的任务:加载数据,下载和上传。
5.2 NSURLSession相关的类
NSURLConnection这个名字,实际上指的是一组构成Foundation框架中URL加载系统的相互关联的组件:NSURLRequest,NSURLResponse,NSURLProtocol,NSURLCache,NSHTTPCookieStorage,NSURLCredentialStorage,以及和它同名的NSURLConnection。
在WWDC2013中,Apple的团队对NSURLConnection进行了重构,并推出了NSURLSession作为替代。
NSURLSession也是一组相互依赖的类,它的大部分组件和NSURLConnection中的组件相同如NSURLRequest,NSURLCache等。而NSURLSession的不同之处在于,它将NSURLConnection替换为NSURLSession和NSURLSessionConfiguration,以及3个NSURLSessionTask的子类:NSURLSessionDataTask, NSURLSessionUploadTask, 和NSURLSessionDownloadTask。
5.2.1 NSURLSessionConfiguration类
5.2.1.1 简介
其中NSURLSessionConfiguration用于配置会话的属性,可以通过该类配置会话的工作模式:
[objc] view plaincopy
1. (NSURLSessionConfiguration *)defaultSessionConfiguration;
2. (NSURLSessionConfiguration *)ephemeralSessionConfiguration;
3. (NSURLSessionConfiguration *)backgroundSessionConfiguration:(NSString *)identifier;
在backgroundSessionConfiguration:方法中的identifier参数指定了会话的ID,用于标记后台的session。
该类的其中两个属性:
[objc] view plaincopy
1. /* allow request to route over cellular. */
2. @property BOOL allowsCellularAccess;
3.
4. /* allows background tasks to be scheduled at the discretion of the system for optimal performance. */
5. @property (getter=isDiscretionary) BOOL discretionary NS_AVAILABLE(NA, 7_0);
allowsCellularAccess 属性指定是否允许使用蜂窝连接, discretionary属性为YES时表示当程序在后台运作时由系统自己选择最佳的网络连接配置,该属性可以节省通过蜂窝连接的带宽。在使用后台传输数据的时候,建议使用discretionary属性,而不是allowsCellularAccess属性,因为它会把WiFi和电源可用性考虑在内。补充:这个标志允许系统为分配任务进行性能优化。这意味着只有当设备有足够电量时,设备才通过Wifi进行数据传输。如果电量低,或者只仅有一个蜂窝连接,传输任务是不会运行的。后台传输总是在discretionary模式下运行。
5.2.1.2 NSURLSessionConfiguration类属性与方法
/*
* Configurationoptions for an NSURLSession. When asession is
* created, a copyof the configuration object is made - you cannot
* modify theconfiguration of a session after it has been created.
*
* The sharedsession uses the global singleton credential, cache
* and cookiestorage objects.
*
* An ephemeralsession has no persistent disk storage for cookies,
* cache orcredentials.
*
* A backgroundsession can be used to perform networking operations
* on behalf of asuspended application, within certain constraints.
*/
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interfaceNSURLSessionConfiguration : NSObject <NSCopying>
(NSURLSessionConfiguration *)defaultSessionConfiguration;
(NSURLSessionConfiguration *)ephemeralSessionConfiguration;
(NSURLSessionConfiguration *)backgroundSessionConfigurationWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_10, 8_0);
/* identifier for the background session configuration */
@property (readonly, copy) NSString *identifier;
/* default cache policy for requests */
@property NSURLRequestCachePolicy requestCachePolicy;
/* default timeout for requests. This will cause a timeout if no data istransmitted for the given timeout value, and is reset whenever data istransmitted. */
@property NSTimeIntervaltimeoutIntervalForRequest;
/* default timeout for requests. This will cause a timeout if a resource isnot able to be retrieved within a given timeout. */
@property NSTimeIntervaltimeoutIntervalForResource;
/* type of service for requests. */
@property NSURLRequestNetworkServiceType networkServiceType;
/* allow request to route over cellular. */
@property BOOLallowsCellularAccess;
/* allows background tasks to be scheduled at thediscretion of the system for optimal performance. */
@property (getter=isDiscretionary)BOOL discretionary NS_AVAILABLE(10_10, 7_0);
/* The identifier of the shared data container into whichfiles in background sessions should be downloaded.
* App extensionswishing to use background sessions *must* set this property to a validcontainer identifier, or
* the session willbe invalidated upon creation.
*/
@property (copy) NSString*sharedContainerIdentifier NS_AVAILABLE(10_10, 8_0);
/*
* Allows the appto be resumed or launched in the background when tasks in background sessionscomplete
* or when auth isrequired. This only applies to configurations created with backgroundSessionConfigurationWithIdentifier:
* and the defaultvalue is YES.
*/
@property BOOLsessionSendsLaunchEvents NS_AVAILABLE(NA, 7_0);
/* The proxy dictionary, as described by<CFNetwork/CFHTTPStream.h> */
@property (copy) NSDictionary*connectionProxyDictionary;
/* The minimum allowable versions of the TLS protocol,from <Security/SecureTransport.h> */
@property SSLProtocolTLSMinimumSupportedProtocol;
/* The maximum allowable versions of the TLS protocol,from <Security/SecureTransport.h> */
@property SSLProtocolTLSMaximumSupportedProtocol;
/* Allow the use of HTTP pipelining */
@property BOOLHTTPShouldUsePipelining;
/* Allow the session to set cookies on requests */
@property BOOLHTTPShouldSetCookies;
/* Policy for accepting cookies. This overrides the policy otherwise specifiedby the cookie storage. */
@property NSHTTPCookieAcceptPolicy HTTPCookieAcceptPolicy;
/* Specifies additional headers which will be set onoutgoing requests.
Note that theseheaders are added to the request only if not already present. */
@property (copy) NSDictionary*HTTPAdditionalHeaders;
/* The maximum number of simultanous persistentconnections per host */
@property NSIntegerHTTPMaximumConnectionsPerHost;
/* The cookie storage object to use, or nil to indicatethat no cookies should be handled */
@property (retain) NSHTTPCookieStorage *HTTPCookieStorage;
/* The credential storage object, or nil to indicate thatno credential storage is to be used */
@property (retain) NSURLCredentialStorage *URLCredentialStorage;
/* The URL resource cache, or nil to indicate that nocaching is to be performed */
@property (retain) NSURLCache *URLCache;
/* An optional array of Class objects which subclassNSURLProtocol.
The Class willbe sent canInitWithRequest: when determining if
an instance ofthe class can be used for a given URL scheme.
You should notuse [NSURLProtocol registerClass:], as that
method willregister your class with the default session rather
than with aninstance of NSURLSession.
CustomNSURLProtocol subclasses are not available to background
sessions.
*/
@property (copy) NSArray*protocolClasses;
@end
5.2.2 NSURLSession类
5.2.2.1 获取NSURLSession类对象有几种方式
获取NSURLSession类对象有几种方式:
[objc] view plaincopy
- /*
- * The shared session uses the currently set global NSURLCache,
- * NSHTTPCookieStorage and NSURLCredentialStorage objects.
- */
- (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.
- */
- (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
- (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;
第一种方式是使用静态的sharedSession方法,该类使用共享的会话,该会话使用全局的Cache,Cookie和证书。
第二种方式是通过sessionWithConfiguration:方法创建对象,也就是创建对应配置的会话,与NSURLSessionConfiguration合作使用。
第三种方式是通过sessionWithConfiguration:delegate:delegateQueue方法创建对象,二三两种方式可以创建一个新会话并定制其会话类型。该方式中指定了session的委托和委托所处的队列。当不再需要连接时,可以调用Session的invalidateAndCancel直接关闭,或者调用finishTasksAndInvalidate等待当前Task结束后关闭。这时Delegate会收到URLSession:didBecomeInvalidWithError:这个事件。Delegate收到这个事件之后会被解引用。
5.2.2.2 成员属性与方法
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interface NSURLSession : NSObject
/*
* The sharedsession uses the currently set global NSURLCache,
*NSHTTPCookieStorage and NSURLCredentialStorage objects.
*/
(NSURLSession *)sharedSession;
/*
* Customization ofNSURLSession occurs during creation of a new session.
* If you only needto use the convenience routines with custom
* configurationoptions it is not necessary to specify a delegate.
* If you dospecify a delegate, the delegate will be retained until after
* the delegate hasbeen sent the URLSession:didBecomeInvalidWithError: message.
*/
(NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration;
(NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configurationdelegate:(id <NSURLSessionDelegate>)delegate delegateQueue:(NSOperationQueue *)queue;
@property (readonly, retain) NSOperationQueue*delegateQueue;
@property (readonly, retain) id <NSURLSessionDelegate> delegate;
@property (readonly, copy) NSURLSessionConfiguration *configuration;
/*
* ThesessionDescription property is available for the developer to
* provide adescriptive label for the session.
*/
@property (copy) NSString*sessionDescription;
/* -finishTasksAndInvalidate returns immediately andexisting tasks will be allowed
* to run tocompletion. New tasks may not becreated. The session
* will continue tomake delegate callbacks until URLSession:didBecomeInvalidWithError:
* has been issued.
*
*-finishTasksAndInvalidate and -invalidateAndCancel do not
* have any effecton the shared session singleton.
*/
- (void)finishTasksAndInvalidate;
/* -invalidateAndCancel acts as-finishTasksAndInvalidate, but issues
* -cancel to alloutstanding tasks for this session. Notetask
* cancellation issubject to the state of the task, and some tasks may
* have alreadyhave completed at the time they are sent -cancel.
*/
- (void)invalidateAndCancel;
- (void)resetWithCompletionHandler:(void (^)(void))completionHandler; /* emptyall cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:.Invokes completionHandler() on the delegate queue if not nil. */
- (void)flushWithCompletionHandler:(void (^)(void))completionHandler; /* flushstorage to disk and clear transient network caches. Invokes completionHandler() on the delegatequeue if not nil. */
- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks))completionHandler; /* invokes completionHandler with outstanding data,upload and download tasks. */
/*
* NSURLSessionTaskobjects are always created in a suspended state and
* must be sent the-resume message before they will execute.
*/
/* Creates a data task with the given request. The request may have a body stream. */
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;
/* Creates a data task to retrieve the contents of thegiven URL. */
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;
/* Creates an upload task with the given request. The body of the request will be created fromthe file referenced by fileURL */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;
/* Creates an upload task with the given request. The body of the request is provided from thebodyData. */
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;
/* Creates an upload task with the given request. The previously set body stream of the request(if any) is ignored and the URLSession:task:needNewBodyStream: delegate will becalled when the body payload is required. */
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest*)request;
/* Creates a download task with the given request. */
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;
/* Creates a download task to download the contents ofthe given URL. */
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
/* Creates a download task with the resume data. If the download cannot be successfully resumed,URLSession:task:didCompleteWithError: will be called. */
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;
@end
5.2.2.3 NSURLSession(NSURLSessionAsynchronousConvenience)
/*
* NSURLSessionconvenience routines deliver results to
* a completionhandler block. These convenienceroutines
* are notavailable to NSURLSessions that are configured
* as backgroundsessions.
*
* Task objects arealways created in a suspended state and
* must be sent the-resume message before they will execute.
*/
@interface NSURLSession(NSURLSessionAsynchronousConvenience)
/*
* data taskconvenience methods. These methodscreate tasks that
* bypass thenormal delegate calls for response and data delivery,
* and provide asimple cancelable asynchronous interface to receiving
* data. Errors will be returned in theNSURLErrorDomain,
* see<Foundation/NSURLError.h>. Thedelegate, if any, will still be
* called forauthentication challenges.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)requestcompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse*response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
/*
* uploadconvenience method.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURLcompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyDatacompletionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
/*
* download taskconvenience methods. When a downloadsuccessfully
* completes, theNSURL will point to a file that must be read or
* copied duringthe invocation of the completion routine. The file
* will be removedautomatically.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)requestcompletionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
- (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse*response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse*response, NSError *error))completionHandler NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
@end
5.2.3 NSURLSessionTask类
5.2.3.1 简介
NSURLSessionTask是一个抽象子类,它有三个子类:NSURLSessionDataTask,NSURLSessionUploadTask和NSURLSessionDownloadTask。这三个类封装了现代应用程序的三个基本网络任务:获取数据,比如JSON或XML,以及上传和下载文件。
下面是其继承关系:
有多种方法创建对应的任务对象:
5.2.3.2 NSURLSessionTask类属性与方法
typedef NS_ENUM(NSInteger,NSURLSessionTaskState) {
NSURLSessionTaskStateRunning = 0, /* The task is currently being serviced bythe session */
NSURLSessionTaskStateSuspended = 1,
NSURLSessionTaskStateCanceling = 2, /* The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError:message. */
NSURLSessionTaskStateCompleted = 3, /* The task has completed and the session will receive no more delegatenotifications */
} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
/*
* NSURLSessionTask- a cancelable object that refers to the lifetime
* of processing agiven request.
*/
NS_CLASS_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0)
@interface NSURLSessionTask: NSObject <NSCopying>
@property (readonly) NSUInteger taskIdentifier; /* an identifier for this task, assigned byand unique to the owning session */
@property (readonly, copy) NSURLRequest*originalRequest;
@property (readonly, copy) NSURLRequest*currentRequest; /* may differ from originalRequest due to http serverredirection */
@property (readonly, copy) NSURLResponse*response; /* maybe nil if no response has been received */
/* Byte count properties may be zero if no body isexpected,
* orNSURLSessionTransferSizeUnknown if it is not possible
* to know how manybytes will be transferred.
*/
/* number of body bytes already received */
@property (readonly) int64_tcountOfBytesReceived;
/* number of body bytes already sent */
@property (readonly) int64_tcountOfBytesSent;
/* number of body bytes we expect to send, derived fromthe Content-Length of the HTTP request */
@property (readonly) int64_tcountOfBytesExpectedToSend;
/* number of byte bytes we expect to receive, usuallyderived from the Content-Length header of an HTTP response. */
@property (readonly) int64_tcountOfBytesExpectedToReceive;
/*
* ThetaskDescription property is available for the developer to
* provide adescriptive label for the task.
*/
@property (copy) NSString*taskDescription;
/* -cancel returns immediately, but marks a task as beingcanceled.
* The task willsignal -URLSession:task:didCompleteWithError: with an
* error value of {NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the taskmay signal other work before it acknowledges the
*cancelation. -cancel may be sent to atask that has been suspended.
*/
- (void)cancel;
/*
* The currentstate of the task within the session.
*/
@property (readonly) NSURLSessionTaskState state;
/*
* The error, ifany, delivered via -URLSession:task:didCompleteWithError:
* This propertywill be nil in the event that no error occured.
*/
@property (readonly, copy) NSError *error;
/*
* Suspending atask will prevent the NSURLSession from continuing to
* load data. There may still be delegate calls made onbehalf of
* this task (forinstance, to report data received while suspending)
* but no furthertransmissions will be made on behalf of the task
* until -resume issent. The timeout timer associated withthe task
* will be disabledwhile a task is suspended. -suspend and -resume are
* nestable.
*/
- (void)suspend;
- (void)resume;
/*
* Sets a scalingfactor for the priority of the task. The scaling factor is a
* value between0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
* priority and 1.0is considered the highest.
*
* The priority isa hint and not a hard requirement of task performance. The
* priority of atask may be changed using this API at any time, but not all
* protocolssupport this; in these cases, the last priority that took effect
* will be used.
*
* If no priorityis specified, the task will operate with the default priority
* as defined bythe constant NSURLSessionTaskPriorityDefault. Two additional
* priority levelsare provided: NSURLSessionTaskPriorityLow and
*NSURLSessionTaskPriorityHigh, but use is not restricted to these.
*/
@property float priority NS_AVAILABLE(10_10, 8_0);
@end
5.2.3.3 NSURLSessionDataTask
通过request对象或url创建:
[objc] view plaincopy
1. /* Creates a data task with the given request. The request may have a body stream. */
2. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request;
3.
4. /* Creates a data task to retrieve the contents of the given URL. */
5. - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url;
通过request对象或url创建,同时指定任务完成后通过completionHandler指定回调的代码块:
[objc] view plaincopy
1. /*
2. * data task convenience methods. These methods create tasks that
3. * bypass the normal delegate calls for response and data delivery,
4. * and provide a simple cancelable asynchronous interface to receiving
5. * data. Errors will be returned in the NSURLErrorDomain,
6. * see <Foundation/NSURLError.h>. The delegate, if any, will still be
7. * called for authentication challenges.
8. */
9. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
10. - (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
5.2.3.4 NSURLSessionUploadTask
通过request创建,在上传时指定文件源或数据源。
[objc] view plaincopy
1. /* Creates an upload task with the given request. The body of the request will be created from the file referenced by fileURL */
2. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;
3.
4. /* Creates an upload task with the given request. The body of the request is provided from the bodyData. */
5. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData;
6.
7. /* Creates an upload task with the given request. The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required. */
8. - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request;
在创建upload task对象时, 通过completionHandler指定任务完成后的回 调代码块:
[objc] view plaincopy
1. /*
2. * upload convenience method.
3. */
4. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
5. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler;
(3)NSURLSessionDownloadTask
[objc] view plaincopy
1. /* Creates a download task with the given request. */
2. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request;
3.
4. /* Creates a download task to download the contents of the given URL. */
5. - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url;
6.
7. /* Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called. */
8. - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData;
下载任务支持断点续传,第三种方式是通过之前已经下载的数据来创建下载任务。
同样地可以通过completionHandler指定任务完成后的回调代码块:
[objc] view plaincopy
1. /*
2. * download task convenience methods. When a download successfully
3. * completes, the NSURL will point to a file that must be read or
4. * copied during the invocation of the completion routine. The file
5. * will be removed automatically.
6. */
7. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
8. - (NSURLSessionDownloadTask *)downloadTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
9. - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData completionHandler:(void (^)(NSURL *location, NSURLResponse *response, NSError *error))completionHandler;
5.2.4 NSURLSessionDelegate协议
NSURLSessionDelegate协议方法
typedef NS_ENUM(NSInteger,NSURLSessionResponseDisposition) {
NSURLSessionResponseCancel = 0, /* Cancel the load, this is the same as -[task cancel] */
NSURLSessionResponseAllow = 1, /* Allow the load to continue */
NSURLSessionResponseBecomeDownload = 2, /* Turn this request into a download */
} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);
/*
*NSURLSessionDelegate specifies the methods that a session delegate
* may respondto. There are both session specificmessages (for
* example,connection based auth) as well as task based messages.
*/
/*
* Messages relatedto the URL session as a whole
*/
@protocol NSURLSessionDelegate<NSObject>
@optional
/* The last message a session receives. A session will only become
* invalid becauseof a systemic error or when it has been
* explicitlyinvalidated, in which case the error parameter will be nil.
*/
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error;
/* If implemented, when a connection level authenticationchallenge
* has occurred,this delegate will be given the opportunity to
* provideauthentication credentials to the underlying
* connection. Sometypes of authentication will apply to more than
* one request on agiven connection to a server (SSL Server Trust
*challenges). If this delegate message isnot implemented, the
* behavior will beto use the default handling, which may involve user
* interaction.
*/
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler;
/* If an application has received an
*-application:handleEventsForBackgroundURLSession:completionHandler:
* message, thesession delegate will receive this message to indicate
* that all messagespreviously enqueued for this session have been
* delivered. At this time it is safe to invoke thepreviously stored
* completionhandler, or to begin any internal updates that will
* result ininvoking the completion handler.
*/
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)sessionNS_AVAILABLE_IOS(7_0);
@end
5.2.5 NSURLSessionTaskDelegate协议
/*
* Messages relatedto the operation of a specific task.
*/
@protocolNSURLSessionTaskDelegate <NSURLSessionDelegate>
@optional
/* An HTTP request is attempting to perform a redirectionto a different
* URL. You mustinvoke the completion routine to allow the
* redirection,allow the redirection with a modified request, or
* pass nil to thecompletionHandler to cause the body of the redirection
* response to bedelivered as the payload of this request. The default
* is to followredirections.
*
* For tasks inbackground sessions, redirections will always be followed and this method willnot be called.
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLRequest *))completionHandler;
/* The task has received a request specificauthentication challenge.
* If this delegateis not implemented, the session specific authentication challenge
* will *NOT* becalled and the behavior will be the same as using the default handling
* disposition.
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler;
/* Sent if a task requires a new, unopened bodystream. This may be
* necessary whenauthentication has failed for any request that
* involves a bodystream.
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler;
/* Sent periodically to notify the delegate of upload progress. This
* information isalso available as properties of the task.
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
/* Sent as the last message related to a specifictask. Error may be
* nil, whichimplies that no error occurred and this task is complete.
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error;
@end
5.2.6 NSURLSessionDataDelegate
/*
* Messages relatedto the operation of a task that delivers data
* directly to thedelegate.
*/
@protocolNSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@optional
/* The task has received a response and no furthermessages will be
* received untilthe completion block is called. The disposition
* allows you tocancel a request or to turn a data task into a
* download task.This delegate message is optional - if you do not
* implement it,you can get the response as a property of the task.
*
* This method willnot be called for background upload tasks (which cannot be converted todownload tasks).
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;
/* Notification that a data task has become a downloadtask. No
* future messageswill be sent to the data task.
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask;
/* Sent when data is available for the delegate toconsume. It is
* assumed that thedelegate will retain and not copy the data. As
* the data may bediscontiguous, you should use
* [NSDataenumerateByteRangesUsingBlock:] to access it.
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data;
/* Invoke the completion routine with a validNSCachedURLResponse to
* allow theresulting data to be cached, or pass nil to prevent
* caching. Notethat there is no guarantee that caching will be
* attempted for agiven resource, and you should not rely on this
* message toreceive the resource data.
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler;
@end
5.2.7 NSURLSessionDownloadDelegate
/*
* Messages relatedto the operation of a task that writes data to a
* file andnotifies the delegate upon completion.
*/
@protocolNSURLSessionDownloadDelegate <NSURLSessionTaskDelegate>
/* Sent when a download task that has completed adownload. The delegate should
* copy or move thefile at the given location to a new location as it will be
* removed when thedelegate message returns. URLSession:task:didCompleteWithError: will
* still be called.
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location;
@optional
/* Sent periodically to notify the delegate of downloadprogress. */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
/* Sent when a download has been resumed. If a downloadfailed with an
* error, the-userInfo dictionary of the error will contain an
*NSURLSessionDownloadTaskResumeData key, whose value is the resume
* data.
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes;
@end
5.3 Session Task
Session Task分为三种Data Task,Upload Task,Download Task。毫无疑问,Session Task是整个NSURLSession架 构的核 心目标。
注意一定要使用resume方法启动任务。(Upload Task和Download Task同理)
5.3.1 创建普通的下载任务
这种下载任务是可以取消的,代码如下:
[objc] view plaincopy
1. - (IBAction)cancellableDownload:(id)sender {
2. if (!self.cancellableTask) {
3. if (!self.currentSession) {
4. [self createCurrentSession];
5. }
6.
7. NSString *imageURLStr = @"https://img.yuanmabao.com/zijie/pic/2022/03/08/222jbn0xgjm.jpg";
8. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
9. self.cancellableTask = [self.currentSession downloadTaskWithRequest:request];
10.
11. [self setDownloadButtonsWithEnabled:NO];
12. self.downloadedImageView.image = nil;
13.
14. [self.cancellableTask resume];
15. }
16. }
如果当前的session为空,首先需要创建一个session(该session使用默认配置模式,其delegate为自己):
[objc] view plaincopy
1. /* 创建当前的session */
2. - (void)createCurrentSession {
3. NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
4. self.currentSession = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:nil];
5. self.currentSession.sessionDescription = kCurrentSession;
6. }
随后创建下载任务并启动。这种任务是可取消的,即下次下载又从0.0%开始:
[objc] view plaincopy
1. if (self.cancellableTask) {
2. [self.cancellableTask cancel];
3. self.cancellableTask = nil;
4. }
5.3.2 创建可恢复的下载任务
可恢复的下载任务支持断点续传,也就是如果暂停当前任务,在下次再执行任务时,将从之前的下载进度中继续进行。因此我们首先需要一个NSData对象来保存已经下载的数据:
[objc] view plaincopy
1. /* 用于可恢复的下载任务的数据 */
2. @property (strong, nonatomic) NSData *partialData;
执行下载任务时,如果是恢复下载,那么就使用downloadTaskWithResumeData:方法根据partialData继续下载。代码如下:
[objc] view plaincopy
1. - (IBAction)resumableDownload:(id)sender {
2. if (!self.resumableTask) {
3. if (!self.currentSession) {
4. [self createCurrentSession];
5. }
6.
7. if (self.partialData) { // 如果是之前被暂停的任务,就从已经保存的数据恢复下载
8. self.resumableTask = [self.currentSession downloadTaskWithResumeData:self.partialData];
9. }
10. else { // 否则创建下载任务
11. NSString *imageURLStr = @"https://img.yuanmabao.com/zijie/pic/2022/03/08/qw1tl3xguwc.jpg";
12. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
13. self.resumableTask = [self.currentSession downloadTaskWithRequest:request];
14. }
15.
16. [self setDownloadButtonsWithEnabled:NO];
17. self.downloadedImageView.image = nil;
18.
19. [self.resumableTask resume];
20. }
21. }
在取消下载任务时,要将partialData数据保存起来,而且不要调用cancel方法:
[objc] view plaincopy
1. else if (self.resumableTask) {
2. [self.resumableTask cancelByProducingResumeData:^(NSData *resumeData) {
3. // 如果是可恢复的下载任务,应该先将数据保存到partialData中,注意在这里不要调用cancel方法
4. self.partialData = resumeData;
5. self.resumableTask = nil;
6. }];
7. }
另外在恢复下载时,NSURLSessionDownloadDelegate中的以下方法将被调用:
[objc] view plaincopy
1. /* 从fileOffset位移处恢复下载任务 */
2. - (void)URLSession:(NSURLSession *)session
3. downloadTask:(NSURLSessionDownloadTask *)downloadTask
4. didResumeAtOffset:(int64_t)fileOffset
5. expectedTotalBytes:(int64_t)expectedTotalBytes {
6. NSLog(@"NSURLSessionDownloadDelegate: Resume download at %lld", fileOffset);
7. }
5.3.3 创建后台下载任务
后台下载任务,顾名思义,当程序进入后台后,下载任务依然继续执行。
首先创建一个后台session单例,这里的Session配置使用后台配置模式,使用backgroundSessinConfiguration:方法配置时应该通过后面的参数为该后台进程指定一个标识符,在有多个后台下载任务时这个标识符就起作用了。
[objc] view plaincopy
1. /* 创建一个后台session单例 */
2. - (NSURLSession *)backgroundSession {
3. static NSURLSession *backgroundSess = nil;
4. static dispatch_once_t onceToken;
5. dispatch_once(&onceToken, ^{
6. NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:kBackgroundSessionID];
7. backgroundSess = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
8. backgroundSess.sessionDescription = kBackgroundSession;
9. });
10.
11. return backgroundSess;
12. }
在创建后台下载任务时,应该使用后台session创建,然后resume。
[objc] view plaincopy
1. - (IBAction)backgroundDownload:(id)sender {
2. NSString *imageURLStr = @"https://img.yuanmabao.com/zijie/pic/2022/03/08/d3lcqjcpqjk.jpg";
3. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURLStr]];
4. self.backgroundTask = [self.backgroundSession downloadTaskWithRequest:request];
5.
6. [self setDownloadButtonsWithEnabled:NO];
7. self.downloadedImageView.image = nil;
8.
9. [self.backgroundTask resume];
10. }
在程序进入后台后,如果下载任务完成,程序委托中的对应方法将被回调:
[objc] view plaincopy
1. /* 后台下载任务完成后,程序被唤醒,该方法将被调用 */
2. - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
3. NSLog(@"Application Delegate: Background download task finished");
4.
5. // 设置回调的完成代码块
6. self.backgroundURLSessionCompletionHandler = completionHandler;
7. }
然后调用NSURLSessionDownloadDelegate中的方法:
以下是
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL*)location中的方法,该方法只有下载成功才被调用:
[objc] view plaincopy
1. else if (session == self.backgroundSession) {
2. self.backgroundTask = nil;
3. AppDelegate *appDelegate = [AppDelegate sharedDelegate];
4. if (appDelegate.backgroundURLSessionCompletionHandler) {
5. // 执行回调代码块
6. void (^handler)() = appDelegate.backgroundURLSessionCompletionHandler;
7. appDelegate.backgroundURLSessionCompletionHandler = nil;
8. handler();
9. }
10. }
另外无论下载成功与否,以下方法都会被调用:
[objc] view plaincopy
1. /* 完成下载任务,无论下载成功还是失败都调用该方法 */
2. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
3. NSLog(@"NSURLSessionDownloadDelegate: Complete task");
4.
5. dispatch_async(dispatch_get_main_queue(), ^{
6. [self setDownloadButtonsWithEnabled:YES];
7. });
8.
9. if (error) {
10. NSLog(@"下载失败:%@", error);
11. [self setDownloadProgress:0.0];
12. self.downloadedImageView.image = nil;
13. }
14. }
取消后台下载任务时直接cancel即可:
[objc] view plaincopy
1. else if (self.backgroundTask) {
2. [self.backgroundTask cancel];
3. self.backgroundTask = nil;
4. }
5.3.4 NSURLSessionDownloadDelegate
为了实现下载进度的显示,需要在委托中的以下方法中实现:
[objc] view plaincopy
1. /* 执行下载任务时有数据写入 */
2. - (void)URLSession:(NSURLSession *)session
3. downloadTask:(NSURLSessionDownloadTask *)downloadTask
4. didWriteData:(int64_t)bytesWritten // 每次写入的data字节数
5. totalBytesWritten:(int64_t)totalBytesWritten // 当前一共写入的data字节数
6. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite // 期望收到的所有data字节数
7. {
8. // 计算当前下载进度并更新视图
9. double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;
10. [self setDownloadProgress:downloadProgress];
11. }
12.
13. /* 根据下载进度更新视图 */
14. - (void)setDownloadProgress:(double)progress {
15. NSString *progressStr = [NSString stringWithFormat:@"%.1f", progress * 100];
16. progressStr = [progressStr stringByAppendingString:@"%"];
17.
18. dispatch_async(dispatch_get_main_queue(), ^{
19. self.downloadingProgressView.progress = progress;
20. self.currentProgress_label.text = progressStr;
21. });
22. }
从已经保存的数据中恢复下载任务的委托方法,fileOffset指定了恢复下载时的文件位移字节数:
[objc] view plaincopy
1. /* Sent when a download has been resumed. If a download failed with an
2. * error, the -userInfo dictionary of the error will contain an
3. * NSURLSessionDownloadTaskResumeData key, whose value is the resume
4. * data.
5. */
6. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
7. didResumeAtOffset:(int64_t)fileOffset
8. expectedTotalBytes:(int64_t)expectedTotalBytes;
只有下载成功才调用的委托方法,在该方法中应该将下载成功后的文件移动到我们想要的目标路径:
[objc] view plaincopy
1. /* Sent when a download task that has completed a download. The delegate should
2. * copy or move the file at the given location to a new location as it will be
3. * removed when the delegate message returns. URLSession:task:didCompleteWithError: will
4. * still be called.
5. */
6. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
7. didFinishDownloadingToURL:(NSURL *)location;
无论下载成功或失败都会调用的方法,类似于try-catch-finally中的finally语句块的执行。如果下载成功,那么error参数的值为nil,否则下载失败,可以通过该参数查看出错信息:
[objc] view plaincopy
1. /* Sent as the last message related to a specific task. Error may be
2. * nil, which implies that no error occurred and this task is complete.
3. */
4. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
5. didCompleteWithError:(NSError *)error;
6 AFURLSessionManager类
6.1 成员属性
6.1.1 NSURLSession属性session
@property (readonly, nonatomic, strong) NSURLSession *session;
6.1.2 线程操作队列属性
@property (readonly, nonatomic, strong) NSOperationQueue*operationQueue;
6.1.3 响应对象反序列化器
@property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
6.1.4 安全策略对象属性
@property (nonatomic, strong) AFSecurityPolicy*securityPolicy;
6.1.5 网络可用性检查对象属性
@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
6.1.6 任务数组
/**
The data, upload,and download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *tasks;
6.1.7 数据请求任务数组
/**
The data taskscurrently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *dataTasks;
6.1.8 上传任务数组
/**
The upload taskscurrently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *uploadTasks;
6.1.9 下载任务数组
/**
The download taskscurrently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray *downloadTasks;
6.1.10 请求完成后线程队列
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queuefor `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong) dispatch_queue_tcompletionQueue;
6.1.11 请求完成后block群组
/**
The dispatch groupfor `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong) dispatch_group_tcompletionGroup;
///---------------------------------
/// @name Working Around System Bugs
///---------------------------------
6.1.12 是否尝试重新创建任务项属性
/**
Whether to attemptto retry creation of upload tasks for background sessions when initial callreturns `nil`. `NO` by default.
@bug As of iOS 7.0,there is a bug where upload tasks created for background tasks are sometimes`nil`. As a workaround, if this property is `YES`, AFNetworking will followApple's recommendation to try creating the task again.
@see https://github.com/AFNetworking/AFNetworking/issues/1675
*/
@property (nonatomic, assign) BOOLattemptsToRecreateUploadTasksForBackgroundSessions;
6.2 成员方法
6.2.1 初始化方法
/**
Creates andreturns a manager for a session created with the specified configuration. Thisis the designated initializer.
@param configurationThe configuration used to create the managed session.
@return A manager fora newly-created session.
*/
- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration;
6.2.2 结束Session方法
/**
Invalidates themanaged session, optionally canceling pending tasks.
@paramcancelPendingTasks Whether or not to cancel pending tasks.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
6.2.3 根据URL请求新建NSURLSessionDataTask方法
/**
Creates an`NSURLSessionDataTask` with the specified request.
@param request TheHTTP request for the request.
@paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse*response, idresponseObject, NSError *error))completionHandler;
6.2.4 【上传】根据本地文件新建NSURLSessionUploadTask对象的方法
/**
Creates an`NSURLSessionUploadTask` with the specified request for a local file.
@param request TheHTTP request for the request.
@param fileURL A URLto the local file to be uploaded.
@param progress Aprogress object monitoring the current upload progress.
@paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.
@see`attemptsToRecreateUploadTasksForBackgroundSessions`
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(NSProgress * __autoreleasing*)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
6.2.5 【上传】根据二级制数据新建NSURLSessionUploadTask对象的方法
/**
Creates an`NSURLSessionUploadTask` with the specified request for an HTTP body.
@param request TheHTTP request for the request.
@param bodyData Adata object containing the HTTP body to be uploaded.
@param progress Aprogress object monitoring the current upload progress.
@paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
6.2.6 【上传】根据流数据新建NSURLSessionUploadTask对象的方法
/**
Creates an`NSURLSessionUploadTask` with the specified streaming request.
@param request TheHTTP request for the request.
@param progress Aprogress object monitoring the current upload progress.
@paramcompletionHandler A block object to be executed when the task finishes. Thisblock has no return value and takes three arguments: the server response, theresponse object created by that serializer, and the error that occurred, ifany.
*/
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler;
6.2.7 【下载】根据URL请求新建NSURLSessionDownloadTask对象的方法
/**
Creates an `NSURLSessionDownloadTask`with the specified request.
@param request TheHTTP request for the request.
@param progress Aprogress object monitoring the current download progress.
@param destination Ablock object to be executed in order to determine the destination of thedownloaded file. This block takes two arguments, the target path & theserver response, and returns the desired file URL of the resulting download.The temporary file used during the download will be automatically deleted afterbeing moved to the returned URL.
@paramcompletionHandler A block to be executed when a task finishes. This block hasno return value and takes three arguments: the server response, the path of thedownloaded file, and the error describing the network or parsing error thatoccurred, if any.
@warning If using abackground `NSURLSessionConfiguration` on iOS, these blocks will be lost whenthe app is terminated. Background sessions may prefer to use`-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving thedownloaded file, rather than the destination block of this method.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
6.2.8 【下载】根据二进制数据新建NSURLSessionDownloadTask对象的方法
/**
Creates an`NSURLSessionDownloadTask` with the specified resume data.
@param resumeData Thedata used to resume downloading.
@param progress Aprogress object monitoring the current download progress.
@param destination Ablock object to be executed in order to determine the destination of thedownloaded file. This block takes two arguments, the target path & theserver response, and returns the desired file URL of the resulting download.The temporary file used during the download will be automatically deleted afterbeing moved to the returned URL.
@paramcompletionHandler A block to be executed when a task finishes. This block hasno return value and takes three arguments: the server response, the path of thedownloaded file, and the error describing the network or parsing error thatoccurred, if any.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(NSProgress * __autoreleasing *)progress
destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
6.2.9 获取上传进度方法
/**
Returns the uploadprogress of the specified task.
@param uploadTask Thesession upload task. Must not be `nil`.
@return An`NSProgress` object reporting the upload progress of a task, or `nil` if theprogress is unavailable.
*/
- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask;
6.2.10 获取下载进度方法
/**
Returns thedownload progress of the specified task.
@param downloadTaskThe session download task. Must not be `nil`.
@return An`NSProgress` object reporting the download progress of a task, or `nil` if theprogress is unavailable.
*/
- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask;
///-----------------------------------------
/// @name Setting Session Delegate Callbacks
///-----------------------------------------
6.2.11 设置Session失效时执行block
/**
Sets a block to beexecuted when the managed session becomes invalid, as handled by the`NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
@param block A blockobject to be executed when the managed session becomes invalid. The block hasno return value, and takes two arguments: the session, and the error related tothe cause of invalidation.
*/
- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session,NSError *error))block;
6.2.12 设置发送认证时执行的block
/**
Sets a block to beexecuted when a connection level authentication challenge has occurred, ashandled by the `NSURLSessionDelegate` method`URLSession:didReceiveChallenge:completionHandler:`.
@param block A blockobject to be executed when a connection level authentication challenge hasoccurred. The block returns the disposition of the authentication challenge,and takes three arguments: the session, the authentication challenge, and apointer to the credential that should be used to resolve the challenge.
*/
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
6.2.13 设置任务请求新流数据包时执行的block
/**
Sets a block to beexecuted when a task requires a new request body stream to send to the remoteserver, as handled by the `NSURLSessionTaskDelegate` method`URLSession:task:needNewBodyStream:`.
@param block A blockobject to be executed when a task requires a new request body stream.
*/
- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session,NSURLSessionTask *task))block;
6.2.14 设置请求重定向时执行的block
/**
Sets a block to beexecuted when an HTTP request is attempting to perform a redirection to adifferent URL, as handled by the `NSURLSessionTaskDelegate` method`URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
@param block A blockobject to be executed when an HTTP request is attempting to perform aredirection to a different URL. The block returns the request to be made forthe redirection, and takes four arguments: the session, the task, theredirection response, and the request corresponding to the redirectionresponse.
*/
- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session,NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
6.2.15 设置认证请求完成时执行的block
/**
Sets a block to beexecuted when a session task has received a request specific authenticationchallenge, as handled by the `NSURLSessionTaskDelegate` method`URLSession:task:didReceiveChallenge:completionHandler:`.
@param block A blockobject to be executed when a session task has received a request specificauthentication challenge. The block returns the disposition of theauthentication challenge, and takes four arguments: the session, the task, theauthentication challenge, and a pointer to the credential that should be usedto resolve the challenge.
*/
- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block;
6.2.16 设置跟踪上传进度时执行的block
/**
Sets a block to beexecuted periodically to track upload progress, as handled by the`NSURLSessionTaskDelegate` method`URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
@param block A blockobject to be called when an undetermined number of bytes have been uploaded tothe server. This block has no return value and takes five arguments: thesession, the task, the number of bytes written since the last time the uploadprogress block was called, the total bytes written, and the total bytesexpected to be written during the request, as initially determined by thelength of the HTTP body. This block may be called multiple times, and willexecute on the main thread.
*/
- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_ttotalBytesExpectedToSend))block;
6.2.17 设置任务接收完最后一条消息后执行的block
/**
Sets a block to beexecuted as the last message related to a specific task, as handled by the`NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
@param block A blockobject to be executed when a session task is completed. The block has no returnvalue, and takes three arguments: the session, the task, and any error thatoccurred in the process of executing the task.
*/
- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block;
///-------------------------------------------
/// @name Setting Data Task Delegate Callbacks
///-------------------------------------------
6.2.18 设置DataTask接收到响应时执行的block
/**
Sets a block to beexecuted when a data task has received a response, as handled by the`NSURLSessionDataDelegate` method`URLSession:dataTask:didReceiveResponse:completionHandler:`.
@param block A blockobject to be executed when a data task has received a response. The blockreturns the disposition of the session response, and takes three arguments: thesession, the data task, and the received response.
*/
- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
6.2.19 设置当一个DataTask转化为DownloadTask时执行的block
/**
Sets a block to beexecuted when a data task has become a download task, as handled by the`NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
@param block A blockobject to be executed when a data task has become a download task. The blockhas no return value, and takes three arguments: the session, the data task, andthe download task it has become.
*/
- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session,NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
6.2.20 设置当一个DataTask收到数据时执行的block
/**
Sets a block to beexecuted when a data task receives data, as handled by the`NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
@param block A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes three arguments: thesession, the data task, and the data received. This block may be calledmultiple times, and will execute on the session manager operation queue.
*/
- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
6.2.21 设置确定一个DataTask的缓存方式时执行的block
/**
Sets a block to beexecuted to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate`method `URLSession:dataTask:willCacheResponse:completionHandler:`.
@param block A blockobject to be executed to determine the caching behavior of a data task. Theblock returns the response to cache, and takes three arguments: the session,the data task, and the proposed cached URL response.
*/
- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
6.2.22 设置当所有消息都传输完成时执行的block
/**
Sets a block to beexecuted once all messages enqueued for a session have been delivered, ashandled by the `NSURLSessionDataDelegate` method`URLSessionDidFinishEventsForBackgroundURLSession:`.
@param block A blockobject to be executed once all messages enqueued for a session have beendelivered. The block has no return value and takes a single argument: thesession.
*/
- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession*session))block;
6.2.23 设置下载完成时执行的block
///-----------------------------------------------
/// @name Setting Download Task Delegate Callbacks
///-----------------------------------------------
/**
Sets a block to beexecuted when a download task has completed a download, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didFinishDownloadingToURL:`.
@param block A blockobject to be executed when a download task has completed. The block returns theURL the download should be moved to, and takes three arguments: the session, thedownload task, and the temporary location of the downloaded file. If the filemanager encounters an error while attempting to move the temporary file to thedestination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will beposted, with the download task as its object, and the user info of the error.
*/
- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session,NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
6.2.24 设置跟踪下载进度时执行的block
/**
Sets a block to beexecuted periodically to track download progress, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`.
@param block A blockobject to be called when an undetermined number of bytes have been downloadedfrom the server. This block has no return value and takes five arguments: thesession, the download task, the number of bytes read since the last time thedownload progress block was called, the total bytes read, and the total bytesexpected to be read during the request, as initially determined by the expectedcontent size of the `NSHTTPURLResponse` object. This block may be calledmultiple times, and will execute on the session manager operation queue.
*/
- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session,NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
6.2.25 设置DownloadTask恢复下载时执行的block
/**
Sets a block to beexecuted when a download task has been resumed, as handled by the`NSURLSessionDownloadDelegate` method`URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
@param block A blockobject to be executed when a download task has been resumed. The block has noreturn value and takes four arguments: the session, the download task, the fileoffset of the resumed download, and the total number of bytes expected to bedownloaded.
*/
- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
7 AFHTTPSessionManager类
7.1 成员属性
7.1.1 域名或顶级目录URL属性
/**
The URL used tomonitor reachability, and construct requests from relative paths in methodslike `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al.convenience methods.
*/
@property (readonly, nonatomic, strong) NSURL *baseURL;
7.1.2 AFHTTP请求序列号器对象属性
/**
Requests createdwith `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`are constructed with a set of default headers using a parameter serializationspecified by this property. By default, this is set to an instance of`AFHTTPRequestSerializer`, which serializes query string parameters for `GET`,`HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP messagebodies.
@warning`requestSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
7.1.3 AFHTTP响应序列号器对象属性
/**
Responses sentfrom the server in data tasks created with`dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / etal. convenience methods are automatically validated and serialized by theresponse serializer. By default, this property is set to an instance of`AFJSONResponseSerializer`.
@warning`responseSerializer` must not be `nil`.
*/
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
7.2 成员方法
7.2.1 单例方法
/**
Creates andreturns an `AFHTTPSessionManager` object.
*/
(instancetype)manager;
7.2.2 初始化方法
/**
Initializes an`AFHTTPSessionManager` object with the specified base URL.
@param url The baseURL for the HTTP client.
@return The newly-initializedHTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url;
/**
Initializes an`AFHTTPSessionManager` object with the specified base URL.
This is thedesignated initializer.
@param url The baseURL for the HTTP client.
@param configurationThe configuration used to create the managed session.
@return Thenewly-initialized HTTP client
*/
- (instancetype)initWithBaseURL:(NSURL *)url
sessionConfiguration:(NSURLSessionConfiguration *)configuration;
7.2.3 Get请求方法
/**
Creates and runs an`NSURLSessionDataTask` with a `GET` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.4 Head请求方法
/**
Creates and runsan `NSURLSessionDataTask` with a `HEAD` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes a single arguments: the data task.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.5 Post请求方法
/**
Creates and runsan `NSURLSessionDataTask` with a `POST` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.6 Post请求方法2
/**
Creates and runsan `NSURLSessionDataTask` with a multipart `POST` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param block A blockthat takes a single argument and appends data to the HTTP body. The blockargument is an object adopting the `AFMultipartFormData` protocol.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.7 Put请求方法
/**
Creates and runsan `NSURLSessionDataTask` with a `PUT` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.8 Patch请求方法
/**
Creates and runsan `NSURLSessionDataTask` with a `PATCH` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, idresponseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
7.2.9 Delete请求方法
/**
Creates and runsan `NSURLSessionDataTask` with a `DELETE` request.
@param URLString TheURL string used to create the request URL.
@param parameters Theparameters to be encoded according to the client request serializer.
@param success Ablock object to be executed when the task finishes successfully. This block hasno return value and takes two arguments: the data task, and the response objectcreated by the client response serializer.
@param failure Ablock object to be executed when the task finishes unsuccessfully, or thatfinishes successfully, but encountered an error while parsing the responsedata. This block has no return value and takes a two arguments: the data taskand the error describing the network or parsing error that occurred.
@see-dataTaskWithRequest:completionHandler:
*/
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
8 参考链接
AFNetworking Class References
http://cocoadocs.org/docsets/AFNetworking/2.4.1/
AFNetworking速成教程
http://blog.csdn.net/ysysbaobei/article/details/17390639
NSURLSession学习笔记(一)简介
http://blog.csdn.net/majiakun1/article/details/38133433
NSURLSession学习笔记(二)Session Task
http://blog.csdn.net/majiakun1/article/details/38133703
AFNetworking 学习笔记
http://blog.csdn.net/ysysbaobei/article/details/17390969
NSOperation
http://nshipster.com/nsoperation/
AFNetworking 2.0简介
https://github.com/NSHipster/articles/blob/zh-Hans/2013-09-16-afnetworking-2.md#afnetworking-的大体思路