AFURLSessionManager.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. // AFURLSessionManager.h
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import <Foundation/Foundation.h>
  22. #import "AFURLResponseSerialization.h"
  23. #import "AFURLRequestSerialization.h"
  24. #import "AFSecurityPolicy.h"
  25. #import "AFCompatibilityMacros.h"
  26. #if !TARGET_OS_WATCH
  27. #import "AFNetworkReachabilityManager.h"
  28. #endif
  29. /**
  30. `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
  31. ## Subclassing Notes
  32. This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead.
  33. ## NSURLSession & NSURLSessionTask Delegate Methods
  34. `AFURLSessionManager` implements the following delegate methods:
  35. ### `NSURLSessionDelegate`
  36. - `URLSession:didBecomeInvalidWithError:`
  37. - `URLSession:didReceiveChallenge:completionHandler:`
  38. - `URLSessionDidFinishEventsForBackgroundURLSession:`
  39. ### `NSURLSessionTaskDelegate`
  40. - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`
  41. - `URLSession:task:didReceiveChallenge:completionHandler:`
  42. - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`
  43. - `URLSession:task:needNewBodyStream:`
  44. - `URLSession:task:didCompleteWithError:`
  45. ### `NSURLSessionDataDelegate`
  46. - `URLSession:dataTask:didReceiveResponse:completionHandler:`
  47. - `URLSession:dataTask:didBecomeDownloadTask:`
  48. - `URLSession:dataTask:didReceiveData:`
  49. - `URLSession:dataTask:willCacheResponse:completionHandler:`
  50. ### `NSURLSessionDownloadDelegate`
  51. - `URLSession:downloadTask:didFinishDownloadingToURL:`
  52. - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`
  53. - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`
  54. If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
  55. ## Network Reachability Monitoring
  56. Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details.
  57. ## NSCoding Caveats
  58. - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`.
  59. ## NSCopying Caveats
  60. - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original.
  61. - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied.
  62. @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.
  63. */
  64. NS_ASSUME_NONNULL_BEGIN
  65. @interface AFURLSessionManager : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
  66. /**
  67. The managed session.
  68. */
  69. @property (readonly, nonatomic, strong) NSURLSession *session;
  70. /**
  71. The operation queue on which delegate callbacks are run.
  72. */
  73. @property (readonly, nonatomic, strong) NSOperationQueue *operationQueue;
  74. /**
  75. Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`.
  76. @warning `responseSerializer` must not be `nil`.
  77. */
  78. @property (nonatomic, strong) id <AFURLResponseSerialization> responseSerializer;
  79. ///-------------------------------
  80. /// @name Managing Security Policy
  81. ///-------------------------------
  82. /**
  83. The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified.
  84. */
  85. @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
  86. #if !TARGET_OS_WATCH
  87. ///--------------------------------------
  88. /// @name Monitoring Network Reachability
  89. ///--------------------------------------
  90. /**
  91. The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default.
  92. */
  93. @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
  94. #endif
  95. ///----------------------------
  96. /// @name Getting Session Tasks
  97. ///----------------------------
  98. /**
  99. The data, upload, and download tasks currently run by the managed session.
  100. */
  101. @property (readonly, nonatomic, strong) NSArray <NSURLSessionTask *> *tasks;
  102. /**
  103. The data tasks currently run by the managed session.
  104. */
  105. @property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
  106. /**
  107. The upload tasks currently run by the managed session.
  108. */
  109. @property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
  110. /**
  111. The download tasks currently run by the managed session.
  112. */
  113. @property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
  114. ///-------------------------------
  115. /// @name Managing Callback Queues
  116. ///-------------------------------
  117. /**
  118. The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
  119. */
  120. @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
  121. /**
  122. The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
  123. */
  124. @property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
  125. ///---------------------
  126. /// @name Initialization
  127. ///---------------------
  128. /**
  129. Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
  130. @param configuration The configuration used to create the managed session.
  131. @return A manager for a newly-created session.
  132. */
  133. - (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
  134. /**
  135. Invalidates the managed session, optionally canceling pending tasks and optionally resets given session.
  136. @param cancelPendingTasks Whether or not to cancel pending tasks.
  137. @param resetSession Whether or not to reset the session of the manager.
  138. */
  139. - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession;
  140. ///-------------------------
  141. /// @name Running Data Tasks
  142. ///-------------------------
  143. /**
  144. Creates an `NSURLSessionDataTask` with the specified request.
  145. @param request The HTTP request for the request.
  146. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
  147. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
  148. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
  149. */
  150. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
  151. uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
  152. downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
  153. completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
  154. ///---------------------------
  155. /// @name Running Upload Tasks
  156. ///---------------------------
  157. /**
  158. Creates an `NSURLSessionUploadTask` with the specified request for a local file.
  159. @param request The HTTP request for the request.
  160. @param fileURL A URL to the local file to be uploaded.
  161. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
  162. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
  163. @see `attemptsToRecreateUploadTasksForBackgroundSessions`
  164. */
  165. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
  166. fromFile:(NSURL *)fileURL
  167. progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
  168. completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
  169. /**
  170. Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
  171. @param request The HTTP request for the request.
  172. @param bodyData A data object containing the HTTP body to be uploaded.
  173. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
  174. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
  175. */
  176. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
  177. fromData:(nullable NSData *)bodyData
  178. progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
  179. completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
  180. /**
  181. Creates an `NSURLSessionUploadTask` with the specified streaming request.
  182. @param request The HTTP request for the request.
  183. @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
  184. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
  185. */
  186. - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
  187. progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
  188. completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
  189. ///-----------------------------
  190. /// @name Running Download Tasks
  191. ///-----------------------------
  192. /**
  193. Creates an `NSURLSessionDownloadTask` with the specified request.
  194. @param request The HTTP request for the request.
  195. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
  196. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
  197. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
  198. @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
  199. */
  200. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
  201. progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
  202. destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
  203. completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
  204. /**
  205. Creates an `NSURLSessionDownloadTask` with the specified resume data.
  206. @param resumeData The data used to resume downloading.
  207. @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
  208. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
  209. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
  210. */
  211. - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
  212. progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
  213. destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
  214. completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
  215. ///---------------------------------
  216. /// @name Getting Progress for Tasks
  217. ///---------------------------------
  218. /**
  219. Returns the upload progress of the specified task.
  220. @param task The session task. Must not be `nil`.
  221. @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
  222. */
  223. - (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
  224. /**
  225. Returns the download progress of the specified task.
  226. @param task The session task. Must not be `nil`.
  227. @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
  228. */
  229. - (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
  230. ///-----------------------------------------
  231. /// @name Setting Session Delegate Callbacks
  232. ///-----------------------------------------
  233. /**
  234. Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
  235. @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
  236. */
  237. - (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
  238. /**
  239. Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
  240. @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
  241. @warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `-setAuthenticationChallengeHandler:` instead.
  242. @see -securityPolicy
  243. @see -setAuthenticationChallengeHandler:
  244. */
  245. - (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
  246. ///--------------------------------------
  247. /// @name Setting Task Delegate Callbacks
  248. ///--------------------------------------
  249. /**
  250. Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
  251. @param block A block object to be executed when a task requires a new request body stream.
  252. */
  253. - (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
  254. /**
  255. Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
  256. @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
  257. */
  258. - (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block;
  259. /**
  260. Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`.
  261. @param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge.
  262. When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options:
  263. 1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials.
  264. 2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error.
  265. 3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface.
  266. 4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`.
  267. If you return anything else from the authentication challenge handler, an exception will be thrown.
  268. For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html).
  269. @see -securityPolicy
  270. */
  271. - (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler;
  272. /**
  273. Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
  274. @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during 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.
  275. */
  276. - (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block;
  277. /**
  278. Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
  279. @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
  280. */
  281. - (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block;
  282. /**
  283. Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`.
  284. @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task.
  285. */
  286. #if AF_CAN_INCLUDE_SESSION_TASK_METRICS
  287. - (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10));
  288. #endif
  289. ///-------------------------------------------
  290. /// @name Setting Data Task Delegate Callbacks
  291. ///-------------------------------------------
  292. /**
  293. Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
  294. @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response.
  295. */
  296. - (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block;
  297. /**
  298. Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`.
  299. @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become.
  300. */
  301. - (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block;
  302. /**
  303. Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`.
  304. @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue.
  305. */
  306. - (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block;
  307. /**
  308. Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`.
  309. @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response.
  310. */
  311. - (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block;
  312. /**
  313. Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`.
  314. @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session.
  315. */
  316. - (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos);
  317. ///-----------------------------------------------
  318. /// @name Setting Download Task Delegate Callbacks
  319. ///-----------------------------------------------
  320. /**
  321. Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`.
  322. @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error.
  323. */
  324. - (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block;
  325. /**
  326. Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
  327. @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue.
  328. */
  329. - (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block;
  330. /**
  331. Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
  332. @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded.
  333. */
  334. - (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block;
  335. @end
  336. ///--------------------
  337. /// @name Notifications
  338. ///--------------------
  339. /**
  340. Posted when a task resumes.
  341. */
  342. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification;
  343. /**
  344. Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task.
  345. */
  346. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification;
  347. /**
  348. Posted when a task suspends its execution.
  349. */
  350. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification;
  351. /**
  352. Posted when a session is invalidated.
  353. */
  354. FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification;
  355. /**
  356. Posted when a session download task finished moving the temporary download file to a specified destination successfully.
  357. */
  358. FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification;
  359. /**
  360. Posted when a session download task encountered an error when moving the temporary download file to a specified destination.
  361. */
  362. FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification;
  363. /**
  364. The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task.
  365. */
  366. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey;
  367. /**
  368. The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized.
  369. */
  370. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey;
  371. /**
  372. The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer.
  373. */
  374. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey;
  375. /**
  376. The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk.
  377. */
  378. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey;
  379. /**
  380. Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists.
  381. */
  382. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey;
  383. /**
  384. The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics`
  385. */
  386. FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics;
  387. NS_ASSUME_NONNULL_END