AFHTTPRequestOperationManager.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // AFHTTPRequestOperationManager.h
  2. //
  3. // Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. #import <Foundation/Foundation.h>
  23. #import <SystemConfiguration/SystemConfiguration.h>
  24. #import <Availability.h>
  25. #if __IPHONE_OS_VERSION_MIN_REQUIRED
  26. #import <MobileCoreServices/MobileCoreServices.h>
  27. #else
  28. #import <CoreServices/CoreServices.h>
  29. #endif
  30. #import "AFHTTPRequestOperation.h"
  31. #import "AFURLResponseSerialization.h"
  32. #import "AFURLRequestSerialization.h"
  33. #import "AFSecurityPolicy.h"
  34. #import "AFNetworkReachabilityManager.h"
  35. /**
  36. `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.
  37. ## Subclassing Notes
  38. 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.
  39. For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
  40. ## Methods to Override
  41. To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
  42. ## Serialization
  43. 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>`.
  44. Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
  45. ## URL Construction Using Relative Paths
  46. 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:`.
  47. Below are a few examples of how `baseURL` and relative paths interact:
  48. NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
  49. [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
  50. [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
  51. [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
  52. [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
  53. [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
  54. [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
  55. 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.
  56. ## Network Reachability Monitoring
  57. 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.
  58. ## NSSecureCoding & NSCopying Caveats
  59. `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:
  60. - Archives and copies of HTTP clients will be initialized with an empty operation queue.
  61. - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
  62. */
  63. @interface AFHTTPRequestOperationManager : NSObject <NSSecureCoding, NSCopying>
  64. /**
  65. 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.
  66. */
  67. @property (readonly, nonatomic, strong) NSURL *baseURL;
  68. /**
  69. 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.
  70. @warning `requestSerializer` must not be `nil`.
  71. */
  72. @property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
  73. /**
  74. 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.
  75. @warning `responseSerializer` must not be `nil`.
  76. */
  77. @property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;
  78. /**
  79. The operation queue on which request operations are scheduled and run.
  80. */
  81. @property (nonatomic, strong) NSOperationQueue *operationQueue;
  82. ///-------------------------------
  83. /// @name Managing URL Credentials
  84. ///-------------------------------
  85. /**
  86. Whether request operations should consult the credential storage for authenticating the connection. `YES` by default.
  87. @see AFURLConnectionOperation -shouldUseCredentialStorage
  88. */
  89. @property (nonatomic, assign) BOOL shouldUseCredentialStorage;
  90. /**
  91. The credential used by request operations for authentication challenges.
  92. @see AFURLConnectionOperation -credential
  93. */
  94. @property (nonatomic, strong) NSURLCredential *credential;
  95. ///-------------------------------
  96. /// @name Managing Security Policy
  97. ///-------------------------------
  98. /**
  99. The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified.
  100. */
  101. @property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
  102. ///------------------------------------
  103. /// @name Managing Network Reachability
  104. ///------------------------------------
  105. /**
  106. The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default.
  107. */
  108. @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
  109. ///-------------------------------
  110. /// @name Managing Callback Queues
  111. ///-------------------------------
  112. /**
  113. The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used.
  114. */
  115. @property (nonatomic, strong) dispatch_queue_t completionQueue;
  116. /**
  117. The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used.
  118. */
  119. @property (nonatomic, strong) dispatch_group_t completionGroup;
  120. ///---------------------------------------------
  121. /// @name Creating and Initializing HTTP Clients
  122. ///---------------------------------------------
  123. /**
  124. Creates and returns an `AFHTTPRequestOperationManager` object.
  125. */
  126. + (instancetype)manager;
  127. /**
  128. Initializes an `AFHTTPRequestOperationManager` object with the specified base URL.
  129. This is the designated initializer.
  130. @param url The base URL for the HTTP client.
  131. @return The newly-initialized HTTP client
  132. */
  133. - (instancetype)initWithBaseURL:(NSURL *)url;
  134. ///---------------------------------------
  135. /// @name Managing HTTP Request Operations
  136. ///---------------------------------------
  137. /**
  138. Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client.
  139. @param request The request object to be loaded asynchronously during execution of the operation.
  140. @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.
  141. @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.
  142. */
  143. - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
  144. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  145. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  146. ///---------------------------
  147. /// @name Making HTTP Requests
  148. ///---------------------------
  149. /**
  150. Creates and runs an `AFHTTPRequestOperation` with a `GET` request.
  151. @param URLString The URL string used to create the request URL.
  152. @param parameters The parameters to be encoded according to the client request serializer.
  153. @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.
  154. @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.
  155. @see -HTTPRequestOperationWithRequest:success:failure:
  156. */
  157. - (AFHTTPRequestOperation *)GET:(NSString *)URLString
  158. parameters:(id)parameters
  159. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  160. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  161. /**
  162. Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request.
  163. @param URLString The URL string used to create the request URL.
  164. @param parameters The parameters to be encoded according to the client request serializer.
  165. @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.
  166. @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.
  167. @see -HTTPRequestOperationWithRequest:success:failure:
  168. */
  169. - (AFHTTPRequestOperation *)HEAD:(NSString *)URLString
  170. parameters:(id)parameters
  171. success:(void (^)(AFHTTPRequestOperation *operation))success
  172. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  173. /**
  174. Creates and runs an `AFHTTPRequestOperation` with a `POST` request.
  175. @param URLString The URL string used to create the request URL.
  176. @param parameters The parameters to be encoded according to the client request serializer.
  177. @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.
  178. @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.
  179. @see -HTTPRequestOperationWithRequest:success:failure:
  180. */
  181. - (AFHTTPRequestOperation *)POST:(NSString *)URLString
  182. parameters:(id)parameters
  183. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  184. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  185. /**
  186. Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request.
  187. @param URLString The URL string used to create the request URL.
  188. @param parameters The parameters to be encoded according to the client request serializer.
  189. @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.
  190. @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.
  191. @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.
  192. @see -HTTPRequestOperationWithRequest:success:failure:
  193. */
  194. - (AFHTTPRequestOperation *)POST:(NSString *)URLString
  195. parameters:(id)parameters
  196. constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
  197. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  198. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  199. /**
  200. Creates and runs an `AFHTTPRequestOperation` with a `PUT` request.
  201. @param URLString The URL string used to create the request URL.
  202. @param parameters The parameters to be encoded according to the client request serializer.
  203. @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.
  204. @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.
  205. @see -HTTPRequestOperationWithRequest:success:failure:
  206. */
  207. - (AFHTTPRequestOperation *)PUT:(NSString *)URLString
  208. parameters:(id)parameters
  209. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  210. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  211. /**
  212. Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request.
  213. @param URLString The URL string used to create the request URL.
  214. @param parameters The parameters to be encoded according to the client request serializer.
  215. @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.
  216. @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.
  217. @see -HTTPRequestOperationWithRequest:success:failure:
  218. */
  219. - (AFHTTPRequestOperation *)PATCH:(NSString *)URLString
  220. parameters:(id)parameters
  221. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  222. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  223. /**
  224. Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request.
  225. @param URLString The URL string used to create the request URL.
  226. @param parameters The parameters to be encoded according to the client request serializer.
  227. @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.
  228. @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.
  229. @see -HTTPRequestOperationWithRequest:success:failure:
  230. */
  231. - (AFHTTPRequestOperation *)DELETE:(NSString *)URLString
  232. parameters:(id)parameters
  233. success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
  234. failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
  235. @end