AFHTTPRequestOperationManager.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // AFHTTPRequestOperationManager.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 <SystemConfiguration/SystemConfiguration.h>
  23. #import <Availability.h>
  24. #if __IPHONE_OS_VERSION_MIN_REQUIRED
  25. #import <MobileCoreServices/MobileCoreServices.h>
  26. #else
  27. #import <CoreServices/CoreServices.h>
  28. #endif
  29. #import "AFHTTPRequestOperation.h"
  30. #import "AFURLResponseSerialization.h"
  31. #import "AFURLRequestSerialization.h"
  32. #import "AFSecurityPolicy.h"
  33. #import "AFNetworkReachabilityManager.h"
  34. #ifndef NS_DESIGNATED_INITIALIZER
  35. #if __has_attribute(objc_designated_initializer)
  36. #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
  37. #else
  38. #define NS_DESIGNATED_INITIALIZER
  39. #endif
  40. #endif
  41. NS_ASSUME_NONNULL_BEGIN
  42. /**
  43. `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management.
  44. ## Subclassing Notes
  45. Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
  46. For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
  47. ## Methods to Override
  48. To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
  49. ## Serialization
  50. Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
  51. Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
  52. ## URL Construction Using Relative Paths
  53. For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`.
  54. Below are a few examples of how `baseURL` and relative paths interact:
  55. NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
  56. [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
  57. [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
  58. [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
  59. [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
  60. [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
  61. [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
  62. Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
  63. ## Network Reachability Monitoring
  64. 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.
  65. ## NSSecureCoding & NSCopying Caveats
  66. `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
  67. - Archives and copies of HTTP clients will be initialized with an empty operation queue.
  68. - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
  69. */
  70. @interface AFHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying>
  71. /**
  72. The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods.
  73. */
  74. @property (readonly, nonatomic, strong, nullable) NSURL *baseURL;
  75. /**
  76. Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified 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 message bodies.
  77. @warning `requestSerializer` must not be `nil`.
  78. */
  79. @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
  80. /**
  81. 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 a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. 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 session task or request operation will be executed; otherwise, the `success` callback will be executed.
  82. @warning `responseSerializer` must not be `nil`.
  83. */
  84. @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
  85. /**
  86. The operation queue on which request operations are scheduled and run.
  87. */
  88. @property (nonatomic, strong) NSOperationQueue *operationQueue;
  89. ///-------------------------------
  90. /// @name Managing URL Credentials
  91. ///-------------------------------
  92. /**
  93. Whether request operations should consult the credential storage for authenticating the connection. `YES` by default.
  94. @see AFURLConnectionOperation -shouldUseCredentialStorage
  95. */
  96. @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
  97. /**
  98. The credential used by request operations for authentication challenges.
  99. @see AFURLConnectionOperation -credential
  100. */
  101. @property (nonatomic, strong, nullable) NSURLCredential *credential;
  102. ///-------------------------------
  103. /// @name Managing Security Policy
  104. ///-------------------------------
  105. /**
  106. The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
  107. */
  108. @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
  109. ///------------------------------------
  110. /// @name Managing Network Reachability
  111. ///------------------------------------
  112. /**
  113. The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default.
  114. */
  115. @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
  116. ///-------------------------------
  117. /// @name Managing Callback Queues
  118. ///-------------------------------
  119. /**
  120. The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used.
  121. */
  122. #if OS_OBJECT_USE_OBJC
  123. @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
  124. #else
  125. @property (nonatomic, assign, nullable) dispatch_queue_t completionQueue;
  126. #endif
  127. /**
  128. The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used.
  129. */
  130. #if OS_OBJECT_USE_OBJC
  131. @property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
  132. #else
  133. @property (nonatomic, assign, nullable) dispatch_group_t completionGroup;
  134. #endif
  135. ///---------------------------------------------
  136. /// @name Creating and Initializing HTTP Clients
  137. ///---------------------------------------------
  138. /**
  139. Creates and returns an `AFHTTPRequestOperationManager` object.
  140. */
  141. + (instancetype)manager;
  142. /**
  143. Initializes an `AFHTTPRequestOperationManager` object with the specified base URL.
  144. This is the designated initializer.
  145. @param url The base URL for the HTTP client.
  146. @return The newly-initialized HTTP client
  147. */
  148. - (instancetype)initWithBaseURL:(nullable NSURL *)url NS_DESIGNATED_INITIALIZER;
  149. ///---------------------------------------
  150. /// @name Managing HTTP Request Operations
  151. ///---------------------------------------
  152. /**
  153. Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client.
  154. @param request The request object to be loaded asynchronously during execution of the operation.
  155. @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
  156. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
  157. */
  158. - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
  159. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  160. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  161. ///---------------------------
  162. /// @name Making HTTP Requests
  163. ///---------------------------
  164. /**
  165. Creates and runs an `AFHTTPRequestOperation` with a `GET` request.
  166. @param URLString The URL string used to create the request URL.
  167. @param parameters The parameters to be encoded according to the client request serializer.
  168. @param success A block 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.
  169. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  170. @see -HTTPRequestOperationWithRequest:success:failure:
  171. */
  172. - (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString
  173. parameters:(nullable id)parameters
  174. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  175. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  176. /**
  177. Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request.
  178. @param URLString The URL string used to create the request URL.
  179. @param parameters The parameters to be encoded according to the client request serializer.
  180. @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation.
  181. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  182. @see -HTTPRequestOperationWithRequest:success:failure:
  183. */
  184. - (nullable AFHTTPRequestOperation *)HEAD:(NSString *)URLString
  185. parameters:(nullable id)parameters
  186. success:(nullable void (^)(AFHTTPRequestOperation *operation))success
  187. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  188. /**
  189. Creates and runs an `AFHTTPRequestOperation` with a `POST` request.
  190. @param URLString The URL string used to create the request URL.
  191. @param parameters The parameters to be encoded according to the client request serializer.
  192. @param success A block 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.
  193. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  194. @see -HTTPRequestOperationWithRequest:success:failure:
  195. */
  196. - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString
  197. parameters:(nullable id)parameters
  198. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  199. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  200. /**
  201. Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request.
  202. @param URLString The URL string used to create the request URL.
  203. @param parameters The parameters to be encoded according to the client request serializer.
  204. @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol.
  205. @param success A block 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.
  206. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  207. @see -HTTPRequestOperationWithRequest:success:failure:
  208. */
  209. - (nullable AFHTTPRequestOperation *)POST:(NSString *)URLString
  210. parameters:(nullable id)parameters
  211. constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> formData))block
  212. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  213. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  214. /**
  215. Creates and runs an `AFHTTPRequestOperation` with a `PUT` request.
  216. @param URLString The URL string used to create the request URL.
  217. @param parameters The parameters to be encoded according to the client request serializer.
  218. @param success A block 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.
  219. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  220. @see -HTTPRequestOperationWithRequest:success:failure:
  221. */
  222. - (nullable AFHTTPRequestOperation *)PUT:(NSString *)URLString
  223. parameters:(nullable id)parameters
  224. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  225. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  226. /**
  227. Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request.
  228. @param URLString The URL string used to create the request URL.
  229. @param parameters The parameters to be encoded according to the client request serializer.
  230. @param success A block 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.
  231. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  232. @see -HTTPRequestOperationWithRequest:success:failure:
  233. */
  234. - (nullable AFHTTPRequestOperation *)PATCH:(NSString *)URLString
  235. parameters:(nullable id)parameters
  236. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  237. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  238. /**
  239. Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request.
  240. @param URLString The URL string used to create the request URL.
  241. @param parameters The parameters to be encoded according to the client request serializer.
  242. @param success A block 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.
  243. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
  244. @see -HTTPRequestOperationWithRequest:success:failure:
  245. */
  246. - (nullable AFHTTPRequestOperation *)DELETE:(NSString *)URLString
  247. parameters:(nullable id)parameters
  248. success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  249. failure:(nullable void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  250. @end
  251. NS_ASSUME_NONNULL_END