Permalink
Browse files

readded example project

  • Loading branch information...
1 parent f3ee0a4 commit d444608573d6f1245f5c972c298b490254fb1224 @rnystrom committed Oct 3, 2012
Showing with 6,599 additions and 0 deletions.
  1. +570 −0 example/WeatherKit/AFNetworking/AFHTTPClient.h
  2. +873 −0 example/WeatherKit/AFNetworking/AFHTTPClient.m
  3. +133 −0 example/WeatherKit/AFNetworking/AFHTTPRequestOperation.h
  4. +354 −0 example/WeatherKit/AFNetworking/AFHTTPRequestOperation.m
  5. +108 −0 example/WeatherKit/AFNetworking/AFImageRequestOperation.h
  6. +237 −0 example/WeatherKit/AFNetworking/AFImageRequestOperation.m
  7. +66 −0 example/WeatherKit/AFNetworking/AFJSONRequestOperation.h
  8. +135 −0 example/WeatherKit/AFNetworking/AFJSONRequestOperation.m
  9. +68 −0 example/WeatherKit/AFNetworking/AFNetworkActivityIndicatorManager.h
  10. +131 −0 example/WeatherKit/AFNetworking/AFNetworkActivityIndicatorManager.m
  11. +44 −0 example/WeatherKit/AFNetworking/AFNetworking.h
  12. +68 −0 example/WeatherKit/AFNetworking/AFPropertyListRequestOperation.h
  13. +145 −0 example/WeatherKit/AFNetworking/AFPropertyListRequestOperation.m
  14. +293 −0 example/WeatherKit/AFNetworking/AFURLConnectionOperation.h
  15. +644 −0 example/WeatherKit/AFNetworking/AFURLConnectionOperation.m
  16. +89 −0 example/WeatherKit/AFNetworking/AFXMLRequestOperation.h
  17. +169 −0 example/WeatherKit/AFNetworking/AFXMLRequestOperation.m
  18. +76 −0 example/WeatherKit/AFNetworking/UIImageView+AFNetworking.h
  19. +184 −0 example/WeatherKit/AFNetworking/UIImageView+AFNetworking.m
  20. +7 −0 example/WeatherKit/README.md
  21. +375 −0 example/WeatherKit/WeatherKit.xcodeproj/project.pbxproj
  22. +7 −0 example/WeatherKit/WeatherKit.xcodeproj/project.xcworkspace/contents.xcworkspacedata
  23. BIN ...Kit.xcodeproj/project.xcworkspace/xcuserdata/curiosity.xcuserdatad/UserInterfaceState.xcuserstate
  24. +59 −0 ...le/WeatherKit/WeatherKit.xcodeproj/xcuserdata/curiosity.xcuserdatad/xcschemes/WeatherKit.xcscheme
  25. +22 −0 ...atherKit/WeatherKit.xcodeproj/xcuserdata/curiosity.xcuserdatad/xcschemes/xcschememanagement.plist
  26. +18 −0 example/WeatherKit/WeatherKit/NSString+StringContains.h
  27. +23 −0 example/WeatherKit/WeatherKit/NSString+StringContains.m
  28. +23 −0 example/WeatherKit/WeatherKit/WKAddress.h
  29. +65 −0 example/WeatherKit/WeatherKit/WKAddress.m
  30. +41 −0 example/WeatherKit/WeatherKit/WKDefines.h
  31. +46 −0 example/WeatherKit/WeatherKit/WKDefines.m
  32. +16 −0 example/WeatherKit/WeatherKit/WKHTTPClient.h
  33. +59 −0 example/WeatherKit/WeatherKit/WKHTTPClient.m
  34. +17 −0 example/WeatherKit/WeatherKit/WKObject.h
  35. +80 −0 example/WeatherKit/WeatherKit/WKObject.m
  36. +84 −0 example/WeatherKit/WeatherKit/WKObservation.h
  37. +188 −0 example/WeatherKit/WeatherKit/WKObservation.m
  38. +7 −0 example/WeatherKit/WeatherKit/WeatherKit-Prefix.pch
  39. +27 −0 example/WeatherKit/WeatherKit/WeatherKit.h
  40. +127 −0 example/WeatherKit/WeatherKit/WeatherKit.m
  41. +47 −0 example/WeatherKit/example.json
  42. +380 −0 example/WeatherKitExample.xcodeproj/project.pbxproj
  43. +7 −0 example/WeatherKitExample.xcodeproj/project.xcworkspace/contents.xcworkspacedata
  44. BIN ...ple.xcodeproj/project.xcworkspace/xcuserdata/curiosity.xcuserdatad/UserInterfaceState.xcuserstate
  45. +10 −0 ...ample.xcodeproj/project.xcworkspace/xcuserdata/curiosity.xcuserdatad/WorkspaceSettings.xcsettings
  46. +5 −0 ...le/WeatherKitExample.xcodeproj/xcuserdata/curiosity.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist
  47. +100 −0 ...WeatherKitExample.xcodeproj/xcuserdata/curiosity.xcuserdatad/xcschemes/WeatherKitExample.xcscheme
  48. +22 −0 ...e/WeatherKitExample.xcodeproj/xcuserdata/curiosity.xcuserdatad/xcschemes/xcschememanagement.plist
  49. BIN example/WeatherKitExample/Default-568h@2x.png
  50. BIN example/WeatherKitExample/Default.png
  51. BIN example/WeatherKitExample/Default@2x.png
  52. +15 −0 example/WeatherKitExample/WKEAppDelegate.h
  53. +46 −0 example/WeatherKitExample/WKEAppDelegate.m
  54. +13 −0 example/WeatherKitExample/WKEViewController.h
  55. +56 −0 example/WeatherKitExample/WKEViewController.m
  56. +40 −0 example/WeatherKitExample/WeatherKitExample-Info.plist
  57. +14 −0 example/WeatherKitExample/WeatherKitExample-Prefix.pch
  58. +2 −0 example/WeatherKitExample/en.lproj/InfoPlist.strings
  59. +146 −0 example/WeatherKitExample/en.lproj/MainStoryboard.storyboard
  60. BIN example/WeatherKitExample/logo
  61. +18 −0 example/WeatherKitExample/main.m
View
570 example/WeatherKit/AFNetworking/AFHTTPClient.h
@@ -0,0 +1,570 @@
+// AFHTTPClient.h
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+@class AFHTTPRequestOperation;
+
+/**
+ `AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
+
+ ## Automatic Content Parsing
+
+ Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
+
+ ## Subclassing Notes
+
+ In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
+
+ ## Methods to Override
+
+ To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
+
+ To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
+
+ ## Default Headers
+
+ By default, `AFHTTPClient` sets the following HTTP headers:
+
+ - `Accept-Encoding: gzip`
+ - `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
+ - `User-Agent: (generated user agent)`
+
+ You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
+
+ ## URL Construction Using Relative Paths
+
+ Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
+
+ NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
+ [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
+ [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
+ [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo
+ [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/
+ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
+
+ Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
+
+ ## NSCoding / NSCopying Conformance
+
+ `AFHTTPClient` conforms to the `NSCoding` 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:
+
+ - Archives and copies of HTTP clients will be initialized with an empty operation queue.
+ - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
+ */
+
+#ifdef _SYSTEMCONFIGURATION_H
+typedef enum {
+ AFNetworkReachabilityStatusUnknown = -1,
+ AFNetworkReachabilityStatusNotReachable = 0,
+ AFNetworkReachabilityStatusReachableViaWWAN = 1,
+ AFNetworkReachabilityStatusReachableViaWiFi = 2,
+} AFNetworkReachabilityStatus;
+#endif
+
+typedef enum {
+ AFFormURLParameterEncoding,
+ AFJSONParameterEncoding,
+ AFPropertyListParameterEncoding,
+} AFHTTPClientParameterEncoding;
+
+@protocol AFMultipartFormData;
+
+@interface AFHTTPClient : NSObject <NSCoding, NSCopying>
+
+///---------------------------------------
+/// @name Accessing HTTP Client Properties
+///---------------------------------------
+
+/**
+ The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
+ */
+@property (readonly, nonatomic) NSURL *baseURL;
+
+/**
+ The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
+ */
+@property (nonatomic, assign) NSStringEncoding stringEncoding;
+
+/**
+ The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body. This is `AFFormURLParameterEncoding` by default.
+
+ @warning JSON encoding will automatically use JSONKit, SBJSON, YAJL, or NextiveJSON, if provided. Otherwise, the built-in `NSJSONSerialization` class is used, if available (iOS 5.0 and Mac OS 10.7). If the build target does not either support `NSJSONSerialization` or include a third-party JSON library, a runtime exception will be thrown when attempting to encode parameters as JSON.
+ */
+@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
+
+/**
+ The operation queue which manages operations enqueued by the HTTP client.
+ */
+@property (readonly, nonatomic) NSOperationQueue *operationQueue;
+
+/**
+ The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
+
+ @warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+#endif
+
+///---------------------------------------------
+/// @name Creating and Initializing HTTP Clients
+///---------------------------------------------
+
+/**
+ Creates and initializes an `AFHTTPClient` object with the specified base URL.
+
+ @param url The base URL for the HTTP client. This argument must not be nil.
+
+ @return The newly-initialized HTTP client
+ */
++ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url;
+
+/**
+ Initializes an `AFHTTPClient` object with the specified base URL.
+
+ @param url The base URL for the HTTP client. This argument must not be nil.
+
+ @discussion This is the designated initializer.
+
+ @return The newly-initialized HTTP client
+ */
+- (id)initWithBaseURL:(NSURL *)url;
+
+///-----------------------------------
+/// @name Managing Reachability Status
+///-----------------------------------
+
+/**
+ Sets a callback to be executed when the network availability of the `baseURL` host changes.
+
+ @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
+
+ @warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
+#endif
+
+///-------------------------------
+/// @name Managing HTTP Operations
+///-------------------------------
+
+/**
+ Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
+
+ @param operationClass The subclass of `AFHTTPRequestOperation` to register
+
+ @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
+
+ @discussion When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
+ */
+- (BOOL)registerHTTPOperationClass:(Class)operationClass;
+
+/**
+ Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
+
+ @param operationClass The subclass of `AFHTTPRequestOperation` to register
+ */
+- (void)unregisterHTTPOperationClass:(Class)operationClass;
+
+///----------------------------------
+/// @name Managing HTTP Header Values
+///----------------------------------
+
+/**
+ Returns the value for the HTTP headers set in request objects created by the HTTP client.
+
+ @param header The HTTP header to return the default value for
+
+ @return The default value for the HTTP header, or `nil` if unspecified
+ */
+- (NSString *)defaultValueForHeader:(NSString *)header;
+
+/**
+ Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
+
+ @param header The HTTP header to set a default value for
+ @param value The value set as default for the specified header, or `nil
+ */
+- (void)setDefaultHeader:(NSString *)header value:(NSString *)value;
+
+/**
+ Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
+
+ @param username The HTTP basic auth username
+ @param password The HTTP basic auth password
+ */
+- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password;
+
+/**
+ Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
+
+ @param token The authentication token
+ */
+- (void)setAuthorizationHeaderWithToken:(NSString *)token;
+
+/**
+ Clears any existing value for the "Authorization" HTTP header.
+ */
+- (void)clearAuthorizationHeader;
+
+///-------------------------------
+/// @name Creating Request Objects
+///-------------------------------
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
+
+ If the HTTP method is `GET`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
+
+ @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`.
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters;
+
+/**
+ Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
+
+ @param method The HTTP method for the request. Must be either `POST`, `PUT`, or `DELETE`.
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @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. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
+
+ @discussion The multipart form data is constructed synchronously in the specified block, so in cases where large amounts of data are being added to the request, you should consider performing this method in the background. Likewise, the form data is constructed in-memory, so it may be advantageous to instead write parts of the form data to a file and stream the request body using the `HTTPBodyStream` property of `NSURLRequest`.
+
+ @warning An exception will be raised if the specified method is not `POST`, `PUT` or `DELETE`.
+
+ @return An `NSMutableURLRequest` object
+ */
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
+
+///-------------------------------
+/// @name Creating HTTP Operations
+///-------------------------------
+
+/**
+ Creates an `AFHTTPRequestOperation`.
+
+ In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
+
+ @param request The request object to be loaded asynchronously during execution of the operation.
+ @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.
+ @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.
+ */
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+///----------------------------------------
+/// @name Managing Enqueued HTTP Operations
+///----------------------------------------
+
+/**
+ Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
+
+ @param operation The HTTP request operation to be enqueued.
+ */
+- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
+
+/**
+ Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
+
+ @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
+ @param path The path to match for the cancelled requests.
+ */
+- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
+
+///---------------------------------------
+/// @name Batching HTTP Request Operations
+///---------------------------------------
+
+/**
+ Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
+
+ @param requests The `NSURLRequest` objects used to create and enqueue operations.
+ @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
+ @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
+
+ @discussion Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
+ */
+- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock;
+
+/**
+ Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
+
+ @param operations The request operations used to be batched and enqueued.
+ @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
+ @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
+ */
+- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock;
+
+///---------------------------
+/// @name Making HTTP Requests
+///---------------------------
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and appended as the query string for the request URL.
+ @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.
+ @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.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)getPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @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.
+ @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.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)postPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @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.
+ @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.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)putPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and appended as the query string for the request URL.
+ @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.
+ @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.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)deletePath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+/**
+ Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
+
+ @param path The path to be appended to the HTTP client's base URL and used as the request URL.
+ @param parameters The parameters to be encoded and set in the request HTTP body.
+ @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.
+ @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.
+
+ @see -HTTPRequestOperationWithRequest:success:failure:
+ */
+- (void)patchPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+@end
+
+///----------------
+/// @name Constants
+///----------------
+
+/**
+ ### Network Reachability
+
+ The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
+
+ enum {
+ AFNetworkReachabilityStatusUnknown,
+ AFNetworkReachabilityStatusNotReachable,
+ AFNetworkReachabilityStatusReachableViaWWAN,
+ AFNetworkReachabilityStatusReachableViaWiFi,
+ }
+
+ `AFNetworkReachabilityStatusUnknown`
+ The `baseURL` host reachability is not known.
+
+ `AFNetworkReachabilityStatusNotReachable`
+ The `baseURL` host cannot be reached.
+
+ `AFNetworkReachabilityStatusReachableViaWWAN`
+ The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
+
+ `AFNetworkReachabilityStatusReachableViaWiFi`
+ The `baseURL` host can be reached via a Wi-Fi connection.
+
+ ### Keys for Notification UserInfo Dictionary
+
+ Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
+
+ `AFNetworkingReachabilityNotificationStatusItem`
+ A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
+ The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
+
+ ### Parameter Encoding
+
+ The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
+
+ enum {
+ AFFormURLParameterEncoding,
+ AFJSONParameterEncoding,
+ AFPropertyListParameterEncoding,
+ }
+
+ `AFFormURLParameterEncoding`
+ Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise.
+
+ `AFJSONParameterEncoding`
+ Parameters are encoded into JSON in the message body.
+
+ `AFPropertyListParameterEncoding`
+ Parameters are encoded into a property list in the message body.
+ */
+
+///----------------
+/// @name Functions
+///----------------
+
+/**
+ Returns a query string constructed by a set of parameters, using the specified encoding.
+
+ @param parameters The parameters used to construct the query string
+ @param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
+
+ @discussion Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
+
+ If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
+
+ @return A percent-escaped query string
+ */
+extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
+
+///--------------------
+/// @name Notifications
+///--------------------
+
+/**
+ Posted when network reachability changes.
+ This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
+
+ @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
+ */
+#ifdef _SYSTEMCONFIGURATION_H
+extern NSString * const AFNetworkingReachabilityDidChangeNotification;
+extern NSString * const AFNetworkingReachabilityNotificationStatusItem;
+#endif
+
+#pragma mark -
+
+/**
+ The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
+ */
+@protocol AFMultipartFormData
+
+/**
+ Appends HTTP headers, followed by the encoded data and the multipart form boundary.
+
+ @param headers The HTTP headers to be appended to the form data.
+ @param body The data to be encoded and appended to the form data.
+ */
+- (void)appendPartWithHeaders:(NSDictionary *)headers
+ body:(NSData *)body;
+
+/**
+ Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ */
+- (void)appendPartWithFormData:(NSData *)data
+ name:(NSString *)name;
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
+
+ @param data The data to be encoded and appended to the form data.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param fileName The filename to be associated with the specified data. This parameter must not be `nil`.
+ @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
+ */
+- (void)appendPartWithFileData:(NSData *)data
+ name:(NSString *)name
+ fileName:(NSString *)fileName
+ mimeType:(NSString *)mimeType;
+
+/**
+ Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
+
+ @param fileURL The URL corresponding to the file whose content will be appended to the form.
+ @param name The name to be associated with the specified data. This parameter must not be `nil`.
+ @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
+
+ @return `YES` if the file data was successfully appended, otherwise `NO`.
+
+ @discussion The filename and MIME type for this data in the form will be automatically generated, using `NSURLResponse` `-suggestedFilename` and `-MIMEType`, respectively.
+ */
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+ name:(NSString *)name
+ error:(NSError **)error;
+
+/**
+ Appends encoded data to the form data.
+
+ @param data The data to be encoded and appended to the form data.
+ */
+- (void)appendData:(NSData *)data;
+
+/**
+ Appends a string to the form data.
+
+ @param string The string to be encoded and appended to the form data.
+ */
+- (void)appendString:(NSString *)string;
+
+@end
View
873 example/WeatherKit/AFNetworking/AFHTTPClient.m
@@ -0,0 +1,873 @@
+// AFHTTPClient.m
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+
+#import "AFHTTPClient.h"
+#import "AFHTTPRequestOperation.h"
+
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <UIKit/UIKit.h>
+#endif
+
+#ifdef _SYSTEMCONFIGURATION_H
+#import <SystemConfiguration/SystemConfiguration.h>
+#import <netinet/in.h>
+#import <netinet6/in6.h>
+#import <arpa/inet.h>
+#import <ifaddrs.h>
+#import <netdb.h>
+#endif
+
+// Workaround for management of dispatch_retain() / dispatch_release() by ARC with iOS 6 / Mac OS X 10.8
+#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && (!defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0)) || \
+ (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8))
+#define AF_DISPATCH_RETAIN_RELEASE 1
+#endif
+
+@interface AFMultipartFormData : NSObject <AFMultipartFormData>
+
+- (id)initWithURLRequest:(NSMutableURLRequest *)request
+ stringEncoding:(NSStringEncoding)encoding;
+
+- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
+
+@end
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
+NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem";
+
+typedef SCNetworkReachabilityRef AFNetworkReachabilityRef;
+typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
+#else
+typedef id AFNetworkReachabilityRef;
+#endif
+
+typedef void (^AFCompletionBlock)(void);
+
+static NSString * AFBase64EncodedStringFromString(NSString *string) {
+ NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
+ NSUInteger length = [data length];
+ NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
+
+ uint8_t *input = (uint8_t *)[data bytes];
+ uint8_t *output = (uint8_t *)[mutableData mutableBytes];
+
+ for (NSUInteger i = 0; i < length; i += 3) {
+ NSUInteger value = 0;
+ for (NSUInteger j = i; j < (i + 3); j++) {
+ value <<= 8;
+ if (j < length) {
+ value |= (0xFF & input[j]);
+ }
+ }
+
+ static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ NSUInteger idx = (i / 3) * 4;
+ output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
+ output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
+ output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
+ output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
+ }
+
+ return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
+}
+
+static NSString * AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
+ // Escape characters that are legal in URIs, but have unintentional semantic significance when used in a query string parameter
+ static NSString * const kAFLegalCharactersToBeEscaped = @":/.?&=;+!@$()~";
+
+ return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding));
+}
+
+#pragma mark -
+
+@interface AFQueryStringPair : NSObject
+@property (readwrite, nonatomic, retain) id field;
+@property (readwrite, nonatomic, retain) id value;
+
+- (id)initWithField:(id)field value:(id)value;
+- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
+
+@end
+
+@implementation AFQueryStringPair
+@synthesize field = _field;
+@synthesize value = _value;
+
+- (id)initWithField:(id)field value:(id)value {
+ self = [super init];
+ if (!self) {
+ return nil;
+ }
+
+ self.field = field;
+ self.value = value;
+
+ return self;
+}
+
+- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
+ return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.field, stringEncoding), AFPercentEscapedQueryStringPairMemberFromStringWithEncoding([self.value description], stringEncoding)];
+}
+
+@end
+
+#pragma mark -
+
+extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
+extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
+
+NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
+ NSMutableArray *mutablePairs = [NSMutableArray array];
+ for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
+ [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
+ }
+
+ return [mutablePairs componentsJoinedByString:@"&"];
+}
+
+NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
+ return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
+}
+
+NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
+ NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
+
+ if([value isKindOfClass:[NSDictionary class]]) {
+ [value enumerateKeysAndObjectsUsingBlock:^(id nestedKey, id nestedValue, BOOL *stop) {
+ [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
+ }];
+ } else if([value isKindOfClass:[NSArray class]]) {
+ [value enumerateObjectsUsingBlock:^(id nestedValue, NSUInteger idx, BOOL *stop) {
+ [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
+ }];
+ } else {
+ [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
+ }
+
+ return mutableQueryStringComponents;
+}
+
+static NSString * AFJSONStringFromParameters(NSDictionary *parameters) {
+ NSError *error = nil;
+ NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];;
+
+ if (!error) {
+ return [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
+ } else {
+ return nil;
+ }
+}
+
+static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) {
+ NSString *propertyListString = nil;
+ NSError *error = nil;
+
+ NSData *propertyListData = [NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
+ if (!error) {
+ propertyListString = [[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] ;
+ }
+
+ return propertyListString;
+}
+
+@interface AFHTTPClient ()
+@property (readwrite, nonatomic) NSURL *baseURL;
+@property (readwrite, nonatomic) NSMutableArray *registeredHTTPOperationClassNames;
+@property (readwrite, nonatomic) NSMutableDictionary *defaultHeaders;
+@property (readwrite, nonatomic) NSOperationQueue *operationQueue;
+#ifdef _SYSTEMCONFIGURATION_H
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability;
+@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
+@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
+#endif
+
+#ifdef _SYSTEMCONFIGURATION_H
+- (void)startMonitoringNetworkReachability;
+- (void)stopMonitoringNetworkReachability;
+#endif
+@end
+
+@implementation AFHTTPClient
+@synthesize baseURL = _baseURL;
+@synthesize stringEncoding = _stringEncoding;
+@synthesize parameterEncoding = _parameterEncoding;
+@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
+@synthesize defaultHeaders = _defaultHeaders;
+@synthesize operationQueue = _operationQueue;
+#ifdef _SYSTEMCONFIGURATION_H
+@synthesize networkReachability = _networkReachability;
+@synthesize networkReachabilityStatus = _networkReachabilityStatus;
+@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock;
+#endif
+
++ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url {
+ return [[self alloc] initWithBaseURL:url];
+}
+
+- (id)initWithBaseURL:(NSURL *)url {
+ self = [super init];
+ if (!self) {
+ return nil;
+ }
+
+ // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
+ if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
+ url = [url URLByAppendingPathComponent:@""];
+ }
+
+ self.baseURL = url;
+
+ self.stringEncoding = NSUTF8StringEncoding;
+ self.parameterEncoding = AFFormURLParameterEncoding;
+
+ self.registeredHTTPOperationClassNames = [NSMutableArray array];
+
+ self.defaultHeaders = [NSMutableDictionary dictionary];
+
+ // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
+ NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
+ [self setDefaultHeader:@"Accept-Language" value:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes]];
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
+ [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]];
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]];
+#endif
+
+#ifdef _SYSTEMCONFIGURATION_H
+ self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
+ [self startMonitoringNetworkReachability];
+#endif
+
+ self.operationQueue = [[NSOperationQueue alloc] init];
+ [self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
+
+ return self;
+}
+
+- (void)dealloc {
+#ifdef _SYSTEMCONFIGURATION_H
+ [self stopMonitoringNetworkReachability];
+#endif
+}
+
+- (NSString *)description {
+ return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue];
+}
+
+#pragma mark -
+
+#ifdef _SYSTEMCONFIGURATION_H
+static BOOL AFURLHostIsIPAddress(NSURL *url) {
+ struct sockaddr_in sa_in;
+ struct sockaddr_in6 sa_in6;
+
+ return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1);
+}
+
+static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
+ BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
+ BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
+ BOOL isNetworkReachable = (isReachable && !needsConnection);
+
+ AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
+ if(isNetworkReachable == NO){
+ status = AFNetworkReachabilityStatusNotReachable;
+ }
+#if TARGET_OS_IPHONE
+ else if((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0){
+ status = AFNetworkReachabilityStatusReachableViaWWAN;
+ }
+#endif
+ else {
+ status = AFNetworkReachabilityStatusReachableViaWiFi;
+ }
+
+ return status;
+}
+
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
+ AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+ AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info;
+ if (block) {
+ block(status);
+ }
+
+ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]];
+}
+
+static const void * AFNetworkReachabilityRetainCallback(const void *info) {
+ return (__bridge_retained const void *)([(__bridge AFNetworkReachabilityStatusBlock)info copy]);
+}
+
+static void AFNetworkReachabilityReleaseCallback(const void *info) {}
+
+- (void)startMonitoringNetworkReachability {
+ [self stopMonitoringNetworkReachability];
+
+ if (!self.baseURL) {
+ return;
+ }
+
+ self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
+
+ AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status){
+ self.networkReachabilityStatus = status;
+ if (self.networkReachabilityStatusBlock) {
+ self.networkReachabilityStatusBlock(status);
+ }
+ };
+
+ SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
+ SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
+ SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
+
+ /* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered.
+ */
+ if (AFURLHostIsIPAddress(self.baseURL)) {
+ SCNetworkReachabilityFlags flags;
+ SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
+ dispatch_async(dispatch_get_main_queue(), ^{
+ AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
+ callback(status);
+ });
+ }
+}
+
+- (void)stopMonitoringNetworkReachability {
+ if (_networkReachability) {
+ SCNetworkReachabilityUnscheduleFromRunLoop(_networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
+ CFRelease(_networkReachability);
+ _networkReachability = NULL;
+ }
+}
+
+- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
+ self.networkReachabilityStatusBlock = block;
+}
+#endif
+
+#pragma mark -
+
+- (BOOL)registerHTTPOperationClass:(Class)operationClass {
+ if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
+ return NO;
+ }
+
+ NSString *className = NSStringFromClass(operationClass);
+ [self.registeredHTTPOperationClassNames removeObject:className];
+ [self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
+
+ return YES;
+}
+
+- (void)unregisterHTTPOperationClass:(Class)operationClass {
+ NSString *className = NSStringFromClass(operationClass);
+ [self.registeredHTTPOperationClassNames removeObject:className];
+}
+
+#pragma mark -
+
+- (NSString *)defaultValueForHeader:(NSString *)header {
+ return [self.defaultHeaders valueForKey:header];
+}
+
+- (void)setDefaultHeader:(NSString *)header value:(NSString *)value {
+ [self.defaultHeaders setValue:value forKey:header];
+}
+
+- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password {
+ NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
+ [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]];
+}
+
+- (void)setAuthorizationHeaderWithToken:(NSString *)token {
+ [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]];
+}
+
+- (void)clearAuthorizationHeader {
+ [self.defaultHeaders removeObjectForKey:@"Authorization"];
+}
+
+#pragma mark -
+
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters
+{
+ NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
+ [request setHTTPMethod:method];
+ [request setAllHTTPHeaderFields:self.defaultHeaders];
+
+ if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"]) {
+ [request setHTTPShouldUsePipelining:YES];
+ }
+
+ if (parameters) {
+ if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
+ url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
+ [request setURL:url];
+ } else {
+ NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
+ switch (self.parameterEncoding) {
+ case AFFormURLParameterEncoding:;
+ [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+ [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
+ break;
+ case AFJSONParameterEncoding:;
+ [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+ [request setHTTPBody:[AFJSONStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
+ break;
+ case AFPropertyListParameterEncoding:;
+ [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
+ [request setHTTPBody:[AFPropertyListStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
+ break;
+ }
+ }
+ }
+
+ return request;
+}
+
+- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block
+{
+ NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
+ __block AFMultipartFormData *formData = [[AFMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
+
+ if (parameters) {
+ for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
+ NSData *data = nil;
+ if ([pair.value isKindOfClass:[NSData class]]) {
+ data = pair.value;
+ } else {
+ data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
+ }
+
+ if (data) {
+ [formData appendPartWithFormData:data name:[pair.field description]];
+ }
+ }
+ }
+
+ if (block) {
+ block(formData);
+ }
+
+ return [formData requestByFinalizingMultipartFormData];
+}
+
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ AFHTTPRequestOperation *operation = nil;
+ NSString *className = nil;
+ NSEnumerator *enumerator = [self.registeredHTTPOperationClassNames reverseObjectEnumerator];
+ while (!operation && (className = [enumerator nextObject])) {
+ Class op_class = NSClassFromString(className);
+ if (op_class && [op_class canProcessRequest:urlRequest]) {
+ operation = [(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest];
+ }
+ }
+
+ if (!operation) {
+ operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
+ }
+
+ [operation setCompletionBlockWithSuccess:success failure:failure];
+
+ return operation;
+}
+
+#pragma mark -
+
+- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
+ [self.operationQueue addOperation:operation];
+}
+
+- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path {
+ for (NSOperation *operation in [self.operationQueue operations]) {
+ if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
+ continue;
+ }
+
+ if ((!method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]]) && [path isEqualToString:[[[(AFHTTPRequestOperation *)operation request] URL] path]]) {
+ [operation cancel];
+ }
+ }
+}
+
+- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock
+{
+ NSMutableArray *mutableOperations = [NSMutableArray array];
+ for (NSURLRequest *request in requests) {
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
+ [mutableOperations addObject:operation];
+ }
+
+ [self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
+}
+
+- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ completionBlock:(void (^)(NSArray *operations))completionBlock
+{
+ __block dispatch_group_t dispatchGroup = dispatch_group_create();
+ NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
+ dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
+ if (completionBlock) {
+ completionBlock(operations);
+ }
+ });
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_release(dispatchGroup);
+#endif
+ }];
+
+ for (AFHTTPRequestOperation *operation in operations) {
+ AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
+ operation.completionBlock = ^{
+ dispatch_queue_t queue = operation.successCallbackQueue ?: dispatch_get_main_queue();
+ dispatch_group_async(dispatchGroup, queue, ^{
+ if (originalCompletionBlock) {
+ originalCompletionBlock();
+ }
+
+ __block NSUInteger numberOfFinishedOperations = 0;
+ [operations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
+ if ([(NSOperation *)obj isFinished]) {
+ numberOfFinishedOperations++;
+ }
+ }];
+
+ if (progressBlock) {
+ progressBlock(numberOfFinishedOperations, [operations count]);
+ }
+
+ dispatch_group_leave(dispatchGroup);
+ });
+ };
+
+ dispatch_group_enter(dispatchGroup);
+ [batchedOperation addDependency:operation];
+
+ [self enqueueHTTPRequestOperation:operation];
+ }
+ [self.operationQueue addOperation:batchedOperation];
+}
+
+#pragma mark -
+
+- (void)getPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self enqueueHTTPRequestOperation:operation];
+}
+
+- (void)postPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self enqueueHTTPRequestOperation:operation];
+}
+
+- (void)putPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self enqueueHTTPRequestOperation:operation];
+}
+
+- (void)deletePath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self enqueueHTTPRequestOperation:operation];
+}
+
+- (void)patchPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
+ success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters];
+ AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
+ [self enqueueHTTPRequestOperation:operation];
+}
+
+#pragma mark - NSCoding
+
+- (id)initWithCoder:(NSCoder *)aDecoder {
+ NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
+
+ self = [self initWithBaseURL:baseURL];
+ if (!self) {
+ return nil;
+ }
+
+ self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"];
+ self.parameterEncoding = [aDecoder decodeIntegerForKey:@"parameterEncoding"];
+ self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"];
+ self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"];
+
+ return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)aCoder {
+ [aCoder encodeObject:self.baseURL forKey:@"baseURL"];
+ [aCoder encodeInteger:self.stringEncoding forKey:@"stringEncoding"];
+ [aCoder encodeInteger:self.parameterEncoding forKey:@"parameterEncoding"];
+ [aCoder encodeObject:self.registeredHTTPOperationClassNames forKey:@"registeredHTTPOperationClassNames"];
+ [aCoder encodeObject:self.defaultHeaders forKey:@"defaultHeaders"];
+}
+
+#pragma mark - NSCopying
+
+- (id)copyWithZone:(NSZone *)zone {
+ AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
+
+ HTTPClient.stringEncoding = self.stringEncoding;
+ HTTPClient.parameterEncoding = self.parameterEncoding;
+ HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames copyWithZone:zone];
+ HTTPClient.defaultHeaders = [self.defaultHeaders copyWithZone:zone];
+#ifdef _SYSTEMCONFIGURATION_H
+ HTTPClient.networkReachabilityStatusBlock = self.networkReachabilityStatusBlock;
+#endif
+ return HTTPClient;
+}
+
+@end
+
+#pragma mark -
+
+static NSString * const kAFMultipartTemporaryFileDirectoryName = @"com.alamofire.uploads";
+
+static NSString * AFMultipartTemporaryFileDirectoryPath() {
+ static NSString *multipartTemporaryFilePath = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ multipartTemporaryFilePath = [[NSTemporaryDirectory() stringByAppendingPathComponent:kAFMultipartTemporaryFileDirectoryName] copy];
+
+ NSError *error = nil;
+ if(![[NSFileManager defaultManager] createDirectoryAtPath:multipartTemporaryFilePath withIntermediateDirectories:YES attributes:nil error:&error]) {
+ NSLog(@"Failed to create multipart temporary file directory at %@", multipartTemporaryFilePath);
+ }
+ });
+
+ return multipartTemporaryFilePath;
+}
+
+static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";
+
+static NSString * const kAFMultipartFormCRLF = @"\r\n";
+
+static inline NSString * AFMultipartFormInitialBoundary() {
+ return [NSString stringWithFormat:@"--%@%@", kAFMultipartFormBoundary, kAFMultipartFormCRLF];
+}
+
+static inline NSString * AFMultipartFormEncapsulationBoundary() {
+ return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF];
+}
+
+static inline NSString * AFMultipartFormFinalBoundary() {
+ return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF];
+}
+
+@interface AFMultipartFormData ()
+@property (readwrite, nonatomic) NSMutableURLRequest *request;
+@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
+@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
+@property (readwrite, nonatomic, copy) NSString *temporaryFilePath;
+@end
+
+@implementation AFMultipartFormData
+@synthesize request = _request;
+@synthesize stringEncoding = _stringEncoding;
+@synthesize outputStream = _outputStream;
+@synthesize temporaryFilePath = _temporaryFilePath;
+
+- (id)initWithURLRequest:(NSMutableURLRequest *)request
+ stringEncoding:(NSStringEncoding)encoding
+{
+ self = [super init];
+ if (!self) {
+ return nil;
+ }
+
+ self.request = request;
+ self.stringEncoding = encoding;
+
+ self.temporaryFilePath = [AFMultipartTemporaryFileDirectoryPath() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
+ self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.temporaryFilePath append:NO];
+
+ NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
+ [self.outputStream scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
+ [self.outputStream open];
+
+ return self;
+}
+
+- (void)dealloc {
+
+ if (_outputStream) {
+ [_outputStream close];
+ }
+
+}
+
+- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
+ // Close the stream and return the original request if no data has been written
+ if ([[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] integerValue] == 0) {
+ [self.outputStream close];
+
+ return self.request;
+ }
+
+ [self appendData:[AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding]];
+
+ [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
+ [self.request setValue:[[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] stringValue] forHTTPHeaderField:@"Content-Length"];
+ [self.request setHTTPBodyStream:[NSInputStream inputStreamWithFileAtPath:self.temporaryFilePath]];
+
+ [self.outputStream close];
+
+ return self.request;
+}
+
+#pragma mark - AFMultipartFormData
+
+- (void)appendBoundary {
+ if ([[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] integerValue] == 0) {
+ [self appendString:AFMultipartFormInitialBoundary()];
+ } else {
+ [self appendString:AFMultipartFormEncapsulationBoundary()];
+ }
+}
+
+- (void)appendPartWithHeaders:(NSDictionary *)headers
+ body:(NSData *)body
+{
+ [self appendBoundary];
+
+ for (NSString *field in [headers allKeys]) {
+ [self appendString:[NSString stringWithFormat:@"%@: %@%@", field, [headers valueForKey:field], kAFMultipartFormCRLF]];
+ }
+
+ [self appendString:kAFMultipartFormCRLF];
+ [self appendData:body];
+}
+
+- (void)appendPartWithFormData:(NSData *)data
+ name:(NSString *)name
+{
+ NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+ [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
+
+ [self appendPartWithHeaders:mutableHeaders body:data];
+}
+
+- (void)appendPartWithFileData:(NSData *)data
+ name:(NSString *)name
+ fileName:(NSString *)fileName
+ mimeType:(NSString *)mimeType
+{
+ NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
+ [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
+ [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
+
+ [self appendPartWithHeaders:mutableHeaders body:data];
+}
+
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+ name:(NSString *)name
+ error:(NSError **)error
+{
+ if (![fileURL isFileURL]) {
+ NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
+ [userInfo setValue:fileURL forKey:NSURLErrorFailingURLErrorKey];
+ [userInfo setValue:NSLocalizedString(@"Expected URL to be a file URL", nil) forKey:NSLocalizedFailureReasonErrorKey];
+ if (error != NULL) {
+ *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
+ }
+
+ return NO;
+ }
+
+ NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL];
+ [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
+
+ NSURLResponse *response = nil;
+ NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
+
+ if (data && response) {
+ [self appendPartWithFileData:data name:name fileName:[response suggestedFilename] mimeType:[response MIMEType]];
+
+ return YES;
+ } else {
+ return NO;
+ }
+}
+
+- (void)appendString:(NSString *)string {
+ [self appendData:[string dataUsingEncoding:self.stringEncoding]];
+}
+
+- (void)appendData:(NSData *)data {
+ if ([data length] == 0) {
+ return;
+ }
+
+ if ([self.outputStream hasSpaceAvailable]) {
+ const uint8_t *dataBuffer = (uint8_t *) [data bytes];
+ [self.outputStream write:&dataBuffer[0] maxLength:[data length]];
+ }
+}
+
+@end
View
133 example/WeatherKit/AFNetworking/AFHTTPRequestOperation.h
@@ -0,0 +1,133 @@
+// AFHTTPRequestOperation.h
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import "AFURLConnectionOperation.h"
+
+/**
+ `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
+ */
+@interface AFHTTPRequestOperation : AFURLConnectionOperation
+
+///----------------------------------------------
+/// @name Getting HTTP URL Connection Information
+///----------------------------------------------
+
+/**
+ The last HTTP response received by the operation's connection.
+ */
+@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
+
+///----------------------------------------------------------
+/// @name Managing And Checking For Acceptable HTTP Responses
+///----------------------------------------------------------
+
+/**
+ A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
+ */
+@property (readonly) BOOL hasAcceptableStatusCode;
+
+/**
+ A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
+ */
+@property (readonly) BOOL hasAcceptableContentType;
+
+/**
+ The callback dispatch queue on success. If `NULL` (default), the main queue is used.
+ */
+@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
+
+/**
+ The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
+ */
+@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
+
+///------------------------------------------------------------
+/// @name Managing Acceptable HTTP Status Codes & Content Types
+///------------------------------------------------------------
+
+/**
+ Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
+
+ By default, this is the range 200 to 299, inclusive.
+ */
++ (NSIndexSet *)acceptableStatusCodes;
+
+/**
+ Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
+
+ @param statusCodes The status codes to be added to the set of acceptable HTTP status codes
+ */
++ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
+
+/**
+ Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
+
+ By default, this is `nil`.
+ */
++ (NSSet *)acceptableContentTypes;
+
+/**
+ Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants.
+
+ @param contentTypes The content types to be added to the set of acceptable MIME types
+ */
++ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
+
+
+///-----------------------------------------------------
+/// @name Determining Whether A Request Can Be Processed
+///-----------------------------------------------------
+
+/**
+ A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
+
+ @param urlRequest The request that is determined to be supported or not supported for this class.
+ */
++ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
+
+///-----------------------------------------------------------
+/// @name Setting Completion Block Success / Failure Callbacks
+///-----------------------------------------------------------
+
+/**
+ Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
+
+ @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
+ @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
+
+ @discussion This method should be overridden in subclasses in order to specify the response object passed into the success block.
+ */
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
+
+@end
+
+///----------------
+/// @name Functions
+///----------------
+
+/**
+ Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
+ */
+extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
+
View
354 example/WeatherKit/AFNetworking/AFHTTPRequestOperation.m
@@ -0,0 +1,354 @@
+// AFHTTPRequestOperation.m
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFHTTPRequestOperation.h"
+#import <objc/runtime.h>
+
+// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
+#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
+#define AF_CAST_TO_BLOCK id
+#else
+#define AF_CAST_TO_BLOCK __bridge void *
+#endif
+
+// Workaround for management of dispatch_retain() / dispatch_release() by ARC with iOS 6 / Mac OS X 10.8
+#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && (!defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0)) || \
+ (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8))
+#define AF_DISPATCH_RETAIN_RELEASE 1
+#endif
+
+NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
+ static NSCharacterSet *_skippedCharacterSet = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ _skippedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@" ,"];
+ });
+
+ if (!string) {
+ return nil;
+ }
+
+ NSScanner *scanner = [NSScanner scannerWithString:string];
+ scanner.charactersToBeSkipped = _skippedCharacterSet;
+
+ NSMutableSet *mutableContentTypes = [NSMutableSet set];
+ while (![scanner isAtEnd]) {
+ NSString *contentType = nil;
+ if ([scanner scanUpToString:@";" intoString:&contentType]) {
+ [scanner scanUpToString:@"," intoString:nil];
+ } else {
+ [scanner scanUpToCharactersFromSet:_skippedCharacterSet intoString:&contentType];
+ }
+
+ if (contentType) {
+ [mutableContentTypes addObject:contentType];
+ }
+ }
+
+ return [NSSet setWithSet:mutableContentTypes];
+}
+
+static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
+ Method originalMethod = class_getClassMethod(klass, selector);
+ IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block);
+ class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
+}
+
+static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
+ NSMutableString *string = [NSMutableString string];
+
+ NSRange range = NSMakeRange([indexSet firstIndex], 1);
+ while (range.location != NSNotFound) {
+ NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
+ while (nextIndex == range.location + range.length) {
+ range.length++;
+ nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
+ }
+
+ if (string.length) {
+ [string appendString:@","];
+ }
+
+ if (range.length == 1) {
+ [string appendFormat:@"%lu", (long)range.location];
+ } else {
+ NSUInteger firstIndex = range.location;
+ NSUInteger lastIndex = firstIndex + range.length - 1;
+ [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex];
+ }
+
+ range.location = nextIndex;
+ range.length = 1;
+ }
+
+ return string;
+}
+
+#pragma mark -
+
+@interface AFHTTPRequestOperation ()
+@property (readwrite, nonatomic, strong) NSURLRequest *request;
+@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response;
+@property (readwrite, nonatomic, strong) NSError *HTTPError;
+@property (assign) long long totalContentLength;
+@property (assign) long long offsetContentLength;
+@end
+
+@implementation AFHTTPRequestOperation
+@synthesize HTTPError = _HTTPError;
+@synthesize successCallbackQueue = _successCallbackQueue;
+@synthesize failureCallbackQueue = _failureCallbackQueue;
+@synthesize totalContentLength = _totalContentLength;
+@synthesize offsetContentLength = _offsetContentLength;
+@dynamic request;
+@dynamic response;
+
+- (void)dealloc {
+ if (_successCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_release(_successCallbackQueue);
+#endif
+ _successCallbackQueue = NULL;
+ }
+
+ if (_failureCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_release(_failureCallbackQueue);
+#endif
+ _failureCallbackQueue = NULL;
+ }
+}
+
+- (NSError *)error {
+ if (self.response && !self.HTTPError) {
+ if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
+ NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
+ [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey];
+ [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
+ [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
+ [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
+
+ if (![self hasAcceptableStatusCode]) {
+ NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
+ [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
+ self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo];
+ } else if (![self hasAcceptableContentType]) {
+ // Don't invalidate content type if there is no content
+ if ([self.responseData length] > 0) {
+ [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
+ self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
+ }
+ }
+ }
+ }
+
+ if (self.HTTPError) {
+ return self.HTTPError;
+ } else {
+ return [super error];
+ }
+}
+
+- (void)pause {
+ unsigned long long offset = 0;
+ if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
+ offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
+ } else {
+ offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
+ }
+
+ NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
+ if ([[self.response allHeaderFields] valueForKey:@"ETag"]) {
+ [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
+ }
+ [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
+ self.request = mutableURLRequest;
+
+ [super pause];
+}
+
+- (BOOL)hasAcceptableStatusCode {
+ if (!self.response) {
+ return NO;
+ }
+
+ NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
+ return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
+}
+
+- (BOOL)hasAcceptableContentType {
+ if (!self.response) {
+ return NO;
+ }
+
+ // According to RFC 2616:
+ // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
+ // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
+ NSString *contentType = [self.response MIMEType];
+ if (!contentType) {
+ contentType = @"application/octet-stream";
+ }
+
+ return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
+}
+
+- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
+ if (successCallbackQueue != _successCallbackQueue) {
+ if (_successCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_release(_successCallbackQueue);
+#endif
+ _successCallbackQueue = NULL;
+ }
+
+ if (successCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_retain(successCallbackQueue);
+#endif
+ _successCallbackQueue = successCallbackQueue;
+ }
+ }
+}
+
+- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
+ if (failureCallbackQueue != _failureCallbackQueue) {
+ if (_failureCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_release(_failureCallbackQueue);
+#endif
+ _failureCallbackQueue = NULL;
+ }
+
+ if (failureCallbackQueue) {
+#if AF_DISPATCH_RETAIN_RELEASE
+ dispatch_retain(failureCallbackQueue);
+#endif
+ _failureCallbackQueue = failureCallbackQueue;
+ }
+ }
+}
+
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+ // completion block is manually nilled out in AFURLConnectionOperation to break the retain cycle.
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-retain-cycles"
+ self.completionBlock = ^ {
+ if ([self isCancelled]) {
+ return;
+ }
+
+ if (self.error) {
+ if (failure) {
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
+ failure(self, self.error);
+ });
+ }
+ } else {
+ if (success) {
+ dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
+ success(self, self.responseData);
+ });
+ }
+ }
+ };
+#pragma clang diagnostic pop
+}
+
+#pragma mark - AFHTTPRequestOperation
+
++ (NSIndexSet *)acceptableStatusCodes {
+ return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
+}
+
++ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
+ NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
+ [mutableStatusCodes addIndexes:statusCodes];
+ AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(id _self) {
+ return mutableStatusCodes;
+ });
+}
+
++ (NSSet *)acceptableContentTypes {
+ return nil;
+}
+
++ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
+ NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
+ [mutableContentTypes unionSet:contentTypes];
+ AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(id _self) {
+ return mutableContentTypes;
+ });
+}
+
++ (BOOL)canProcessRequest:(NSURLRequest *)request {
+ if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
+ return YES;
+ }
+
+ return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
+}
+
+#pragma mark - NSURLConnectionDelegate
+
+- (void)connection:(NSURLConnection *)connection
+didReceiveResponse:(NSURLResponse *)response
+{
+ self.response = (NSHTTPURLResponse *)response;
+
+ // Set Content-Range header if status code of response is 206 (Partial Content)
+ // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
+ long long totalContentLength = self.response.expectedContentLength;
+ long long fileOffset = 0;
+ NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
+ if (statusCode == 206) {
+ NSString *contentRange = [self.response.allHeaderFields valueForKey:@"Content-Range"];
+ if ([contentRange hasPrefix:@"bytes"]) {
+ NSArray *byteRanges = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
+ if ([byteRanges count] == 4) {
+ fileOffset = [[byteRanges objectAtIndex:1] longLongValue];
+ totalContentLength = [[byteRanges objectAtIndex:2] longLongValue] ?: -1; // if this is "*", it's converted to 0, but -1 is default.
+ }
+ }
+ } else {
+ if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
+ [self.outputStream setProperty:[NSNumber numberWithInteger:0] forKey:NSStreamFileCurrentOffsetKey];
+ } else {
+ if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) {
+ self.outputStream = [NSOutputStream outputStreamToMemory];
+
+ NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
+ for (NSString *runLoopMode in self.runLoopModes) {
+ [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
+ }
+ }
+ }
+ }
+
+ self.offsetContentLength = MAX(fileOffset, 0);
+ self.totalContentLength = totalContentLength;
+
+ [self.outputStream open];
+}
+
+@end
View
108 example/WeatherKit/AFNetworking/AFImageRequestOperation.h
@@ -0,0 +1,108 @@
+// AFImageRequestOperation.h
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import <Foundation/Foundation.h>
+#import "AFHTTPRequestOperation.h"
+
+#import <Availability.h>
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+#import <UIKit/UIKit.h>
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+#import <Cocoa/Cocoa.h>
+#endif
+
+/**
+ `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
+
+ ## Acceptable Content Types
+
+ By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
+
+ - `image/tiff`
+ - `image/jpeg`
+ - `image/gif`
+ - `image/png`
+ - `image/ico`
+ - `image/x-icon`
+ - `image/bmp`
+ - `image/x-bmp`
+ - `image/x-xbitmap`
+ - `image/x-win-bitmap`
+ */
+@interface AFImageRequestOperation : AFHTTPRequestOperation
+
+/**
+ An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
+ */
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+@property (readonly, nonatomic) UIImage *responseImage;
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+@property (readonly, nonatomic, retain) NSImage *responseImage;
+#endif
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+/**
+ The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance.
+ */
+@property (nonatomic, assign) CGFloat imageScale;
+#endif
+
+/**
+ Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
+
+ @param urlRequest The request object to be loaded asynchronously during execution of the operation.
+ @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single arguments, the image created from the response data of the request.
+
+ @return A new image request operation
+ */
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(UIImage *image))success;
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(NSImage *image))success;
+#endif
+
+/**
+ Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
+
+ @param urlRequest The request object to be loaded asynchronously during execution of the operation.
+ @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
+ @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
+ @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
+
+ @return A new image request operation
+ */
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
+ success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
+ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
+ success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
+ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
+#endif
+
+@end
View
237 example/WeatherKit/AFNetworking/AFImageRequestOperation.m
@@ -0,0 +1,237 @@
+// AFImageRequestOperation.m
+//
+// Copyright (c) 2011 Gowalla (http://gowalla.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+#import "AFImageRequestOperation.h"
+
+static dispatch_queue_t af_image_request_operation_processing_queue;
+static dispatch_queue_t image_request_operation_processing_queue() {
+ if (af_image_request_operation_processing_queue == NULL) {
+ af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
+ }
+
+ return af_image_request_operation_processing_queue;
+}
+
+@interface AFImageRequestOperation ()
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+@property (readwrite, nonatomic) UIImage *responseImage;
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+@property (readwrite, nonatomic, retain) NSImage *responseImage;
+#endif
+@end
+
+@implementation AFImageRequestOperation
+@synthesize responseImage = _responseImage;
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+@synthesize imageScale = _imageScale;
+#endif
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(UIImage *image))success
+{
+ return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
+ if (success) {
+ success(image);
+ }
+ } failure:nil];
+}
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ success:(void (^)(NSImage *image))success
+{
+ return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
+ if (success) {
+ success(image);
+ }
+ } failure:nil];
+}
+#endif
+
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
+ success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
+ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
+{
+ AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
+ [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+ if (success) {
+ UIImage *image = responseObject;
+ if (imageProcessingBlock) {
+ dispatch_async(image_request_operation_processing_queue(), ^(void) {
+ UIImage *processedImage = imageProcessingBlock(image);
+
+ dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
+ success(operation.request, operation.response, processedImage);
+ });
+ });
+ } else {
+ success(operation.request, operation.response, image);
+ }
+ }
+ } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+ if (failure) {
+ failure(operation.request, operation.response, error);
+ }
+ }];
+
+
+ return requestOperation;
+}
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
+ success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
+ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
+{
+ AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
+ [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
+ if (success) {
+ NSImage *image = responseObject;
+ if (imageProcessingBlock) {
+ dispatch_async(image_request_operation_processing_queue(), ^(void) {
+ NSImage *processedImage = imageProcessingBlock(image);
+
+ dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
+ success(operation.request, operation.response, processedImage);
+ });
+ });
+ } else {
+ success(operation.request, operation.response, image);
+ }
+ }
+ } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
+ if (failure) {
+ failure(operation.request, operation.response, error);
+ }
+ }];
+
+ return requestOperation;
+}
+#endif
+
+- (id)initWithRequest:(NSURLRequest *)urlRequest {
+ self = [super initWithRequest:urlRequest];
+ if (!self) {
+ return nil;
+ }
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ self.imageScale = [[UIScreen mainScreen] scale];
+#endif
+
+ return self;
+}
+
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+- (UIImage *)responseImage {
+ if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
+ UIImage *image = [UIImage imageWithData:self.responseData];
+
+ self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
+ }
+
+ return _responseImage;
+}
+
+- (void)setImageScale:(CGFloat)imageScale {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wfloat-equal"
+ if (imageScale == _imageScale) {
+ return;
+ }
+#pragma clang diagnostic pop
+
+ _imageScale = imageScale;
+
+ self.responseImage = nil;
+}
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+- (NSImage *)responseImage {
+ if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
+ // Ensure that the image is set to it's correct pixel width and height
+ NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
+ self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
+ [self.responseImage addRepresentation:bitimage];
+ }
+
+ return _responseImage;
+}
+#endif
+
+#pragma mark - AFHTTPRequestOperation
+
++ (NSSet *)acceptableContentTypes {
+ return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
+}
+
++ (BOOL)canProcessRequest:(NSURLRequest *)request {
+ static NSSet * _acceptablePathExtension = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
+ });
+
+ return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
+}
+
+- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
+ failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
+{
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-retain-cycles"
+ self.completionBlock = ^ {
+ if ([self isCancelled]) {
+ return;
+ }
+
+ dispatch_async(image_request_operation_processing_queue(), ^(void) {
+ if (self.error) {
+ if (failure) {
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
+ failure(self, self.error);
+ });
+ }
+ } else {
+ if (success) {
+#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ UIImage *image = nil;
+#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ NSImage *image = nil;
+#endif
+
+ image = self.responseImage;
+
+ dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
+ success(self, image);
+ });
+ }
+ }
+ });