AFURLConnectionOperation.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // AFURLConnectionOperation.h
  2. // Copyright (c) 2011–2015 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 <Availability.h>
  23. #import "AFURLRequestSerialization.h"
  24. #import "AFURLResponseSerialization.h"
  25. #import "AFSecurityPolicy.h"
  26. #ifndef NS_DESIGNATED_INITIALIZER
  27. #if __has_attribute(objc_designated_initializer)
  28. #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
  29. #else
  30. #define NS_DESIGNATED_INITIALIZER
  31. #endif
  32. #endif
  33. /**
  34. `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
  35. ## Subclassing Notes
  36. This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
  37. If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
  38. ## NSURLConnection Delegate Methods
  39. `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
  40. - `connection:didReceiveResponse:`
  41. - `connection:didReceiveData:`
  42. - `connectionDidFinishLoading:`
  43. - `connection:didFailWithError:`
  44. - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
  45. - `connection:willCacheResponse:`
  46. - `connectionShouldUseCredentialStorage:`
  47. - `connection:needNewBodyStream:`
  48. - `connection:willSendRequestForAuthenticationChallenge:`
  49. If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
  50. ## Callbacks and Completion Blocks
  51. The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
  52. Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
  53. ## SSL Pinning
  54. Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle.
  55. SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice.
  56. Connections will be validated on all matching certificates with a `.cer` extension in the bundle root.
  57. ## App Extensions
  58. When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs.
  59. ## NSCoding & NSCopying Conformance
  60. `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
  61. ### NSCoding Caveats
  62. - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
  63. - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
  64. ### NSCopying Caveats
  65. - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
  66. - A copy of an operation will not include the `outputStream` of the original.
  67. - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
  68. */
  69. @interface AFURLConnectionOperation : NSOperation <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSSecureCoding, NSCopying>
  70. ///-------------------------------
  71. /// @name Accessing Run Loop Modes
  72. ///-------------------------------
  73. /**
  74. The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
  75. */
  76. @property (nonatomic, strong) NSSet *runLoopModes;
  77. ///-----------------------------------------
  78. /// @name Getting URL Connection Information
  79. ///-----------------------------------------
  80. /**
  81. The request used by the operation's connection.
  82. */
  83. @property (readonly, nonatomic, strong) NSURLRequest *request;
  84. /**
  85. The last response received by the operation's connection.
  86. */
  87. @property (readonly, nonatomic, strong) NSURLResponse *response;
  88. /**
  89. The error, if any, that occurred in the lifecycle of the request.
  90. */
  91. @property (readonly, nonatomic, strong) NSError *error;
  92. ///----------------------------
  93. /// @name Getting Response Data
  94. ///----------------------------
  95. /**
  96. The data received during the request.
  97. */
  98. @property (readonly, nonatomic, strong) NSData *responseData;
  99. /**
  100. The string representation of the response data.
  101. */
  102. @property (readonly, nonatomic, copy) NSString *responseString;
  103. /**
  104. The string encoding of the response.
  105. If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
  106. */
  107. @property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
  108. ///-------------------------------
  109. /// @name Managing URL Credentials
  110. ///-------------------------------
  111. /**
  112. Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
  113. This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
  114. */
  115. @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
  116. /**
  117. The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
  118. This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
  119. */
  120. @property (nonatomic, strong) NSURLCredential *credential;
  121. ///-------------------------------
  122. /// @name Managing Security Policy
  123. ///-------------------------------
  124. /**
  125. The security policy used to evaluate server trust for secure connections.
  126. */
  127. @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
  128. ///------------------------
  129. /// @name Accessing Streams
  130. ///------------------------
  131. /**
  132. The input stream used to read data to be sent during the request.
  133. This property acts as a proxy to the `HTTPBodyStream` property of `request`.
  134. */
  135. @property (nonatomic, strong) NSInputStream *inputStream;
  136. /**
  137. The output stream that is used to write data received until the request is finished.
  138. By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
  139. */
  140. @property (nonatomic, strong) NSOutputStream *outputStream;
  141. ///---------------------------------
  142. /// @name Managing Callback Queues
  143. ///---------------------------------
  144. /**
  145. The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
  146. */
  147. #if OS_OBJECT_HAVE_OBJC_SUPPORT
  148. @property (nonatomic, strong) dispatch_queue_t completionQueue;
  149. #else
  150. @property (nonatomic, assign) dispatch_queue_t completionQueue;
  151. #endif
  152. /**
  153. The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
  154. */
  155. #if OS_OBJECT_HAVE_OBJC_SUPPORT
  156. @property (nonatomic, strong) dispatch_group_t completionGroup;
  157. #else
  158. @property (nonatomic, assign) dispatch_group_t completionGroup;
  159. #endif
  160. ///---------------------------------------------
  161. /// @name Managing Request Operation Information
  162. ///---------------------------------------------
  163. /**
  164. The user info dictionary for the receiver.
  165. */
  166. @property (nonatomic, strong) NSDictionary *userInfo;
  167. ///------------------------------------------------------
  168. /// @name Initializing an AFURLConnectionOperation Object
  169. ///------------------------------------------------------
  170. /**
  171. Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
  172. This is the designated initializer.
  173. @param urlRequest The request object to be used by the operation connection.
  174. */
  175. - (instancetype)initWithRequest:(NSURLRequest *)urlRequest NS_DESIGNATED_INITIALIZER;
  176. ///----------------------------------
  177. /// @name Pausing / Resuming Requests
  178. ///----------------------------------
  179. /**
  180. Pauses the execution of the request operation.
  181. A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
  182. */
  183. - (void)pause;
  184. /**
  185. Whether the request operation is currently paused.
  186. @return `YES` if the operation is currently paused, otherwise `NO`.
  187. */
  188. - (BOOL)isPaused;
  189. /**
  190. Resumes the execution of the paused request operation.
  191. Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
  192. */
  193. - (void)resume;
  194. ///----------------------------------------------
  195. /// @name Configuring Backgrounding Task Behavior
  196. ///----------------------------------------------
  197. /**
  198. Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
  199. @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
  200. */
  201. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS)
  202. - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
  203. #endif
  204. ///---------------------------------
  205. /// @name Setting Progress Callbacks
  206. ///---------------------------------
  207. /**
  208. Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
  209. @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 three arguments: 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.
  210. */
  211. - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
  212. /**
  213. Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
  214. @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 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 main thread.
  215. */
  216. - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
  217. ///-------------------------------------------------
  218. /// @name Setting NSURLConnection Delegate Callbacks
  219. ///-------------------------------------------------
  220. /**
  221. Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`.
  222. @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol).
  223. If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
  224. */
  225. - (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
  226. /**
  227. Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`.
  228. @param block A block object 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 URL response that caused the redirect.
  229. */
  230. - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
  231. /**
  232. Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
  233. @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
  234. */
  235. - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
  236. ///
  237. /**
  238. */
  239. + (NSArray *)batchOfRequestOperations:(NSArray *)operations
  240. progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
  241. completionBlock:(void (^)(NSArray *operations))completionBlock;
  242. @end
  243. ///--------------------
  244. /// @name Notifications
  245. ///--------------------
  246. /**
  247. Posted when an operation begins executing.
  248. */
  249. extern NSString * const AFNetworkingOperationDidStartNotification;
  250. /**
  251. Posted when an operation finishes.
  252. */
  253. extern NSString * const AFNetworkingOperationDidFinishNotification;