Skip to content
Browse files

Merge branch 'master' into geo-position-header

  • Loading branch information...
2 parents 637f8fb + c838016 commit f5ef7ba1b07fe74834346fbb4c67b728e33982f6 @mattt mattt committed
Showing with 819 additions and 999 deletions.
  1. +5 −5 AFNetworking.podspec
  2. +162 −108 AFNetworking/AFHTTPClient.h
  3. +169 −159 AFNetworking/AFHTTPClient.m
  4. +17 −38 AFNetworking/AFHTTPRequestOperation.h
  5. +82 −83 AFNetworking/AFHTTPRequestOperation.m
  6. +2 −6 AFNetworking/AFImageRequestOperation.h
  7. +13 −15 AFNetworking/AFImageRequestOperation.m
  8. +2 −2 AFNetworking/AFJSONRequestOperation.h
  9. +12 −15 AFNetworking/AFJSONRequestOperation.m
  10. +0 −26 AFNetworking/AFJSONUtilities.h
  11. +0 −217 AFNetworking/AFJSONUtilities.m
  12. +5 −7 AFNetworking/AFNetworkActivityIndicatorManager.m
  13. +1 −1 AFNetworking/AFPropertyListRequestOperation.h
  14. +10 −12 AFNetworking/AFPropertyListRequestOperation.m
  15. +72 −67 AFNetworking/AFURLConnectionOperation.h
  16. +120 −85 AFNetworking/AFURLConnectionOperation.m
  17. +2 −2 AFNetworking/AFXMLRequestOperation.h
  18. +12 −20 AFNetworking/AFXMLRequestOperation.m
  19. +7 −5 AFNetworking/UIImageView+AFNetworking.m
  20. +14 −0 CHANGES
  21. +12 −0 Example/AFNetworking Example.entitlements
  22. +58 −62 Example/AFNetworking Mac Example.xcodeproj/project.pbxproj
  23. +13 −19 Example/AFNetworking iOS Example.xcodeproj/project.pbxproj
  24. +1 −1 Example/AppDelegate.h
  25. +7 −3 Example/AppDelegate.m
  26. +4 −2 Example/Classes/Controllers/PublicTimelineViewController.m
  27. +4 −4 Example/Classes/Models/Tweet.h
  28. +5 −16 Example/Classes/Models/Tweet.m
  29. +1 −1 Example/Classes/Models/User.h
  30. +2 −0 Example/Classes/Models/User.m
  31. BIN Example/Icon.png
  32. BIN Example/Icon@2x.png
  33. +3 −3 Example/iOS-Info.plist
  34. +2 −15 README.md
View
10 AFNetworking.podspec
@@ -1,12 +1,12 @@
Pod::Spec.new do |s|
s.name = 'AFNetworking'
- s.version = '0.10.0'
+ s.version = '1.0RC2'
s.license = 'MIT'
- s.summary = 'A delightful iOS and OS X networking framework'
+ s.summary = 'A delightful iOS and OS X networking framework.'
s.homepage = 'https://github.com/AFNetworking/AFNetworking'
- s.authors = {'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@gowalla.com'}
- s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '0.10.0' }
+ s.authors = {'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@scottraymond.net'}
+ s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '1.0RC2' }
s.source_files = 'AFNetworking'
- s.clean_paths = ['iOS Example', 'Mac Example', 'AFNetworking.xcworkspace']
s.framework = 'SystemConfiguration'
+ s.prefix_header_contents = "#import <SystemConfiguration/SystemConfiguration.h>"
end
View
270 AFNetworking/AFHTTPClient.h
@@ -23,74 +23,13 @@
#import <Foundation/Foundation.h>
@class AFHTTPRequestOperation;
-@protocol AFHTTPClientOperation;
-@protocol AFMultipartFormData;
-
-/**
- Posted when network reachability changes.
- The notification object is an `NSNumber` object containing the boolean value for the current network reachability.
- This notification contains no information in the `userInfo` dictionary.
-
- @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;
-#endif
-
-/**
- Specifies network reachability of the client to its `baseURL` domain.
- */
-#ifdef _SYSTEMCONFIGURATION_H
-typedef enum {
- AFNetworkReachabilityStatusUnknown = -1,
- AFNetworkReachabilityStatusNotReachable = 0,
- AFNetworkReachabilityStatusReachableViaWWAN = 1,
- AFNetworkReachabilityStatusReachableViaWiFi = 2,
-} AFNetworkReachabilityStatus;
-#endif
-
-/**
- Specifies the method used to encode parameters into request body.
- */
-typedef enum {
- AFFormURLParameterEncoding,
- AFJSONParameterEncoding,
- AFPropertyListParameterEncoding,
-} AFHTTPClientParameterEncoding;
-
-/**
- Returns a string, replacing certain characters with the equivalent percent escape sequence based on the specified encoding.
-
- @param string The string to URL encode
- @param encoding The encoding to use for the replacement. 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 The characters escaped are all characters that are not legal URL characters (based on RFC 3986), including any whitespace, punctuation, or special characters.
-
- @return A URL-encoded string. If it does not need to be modified (no percent escape sequences are missing), this function may merely return string argument.
- */
-extern NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding);
-
-/**
- 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, URL-encoding a string representation of the key-value pair, and then joining the components with "&".
-
-
- If a key-value pair has a an `NSArray` for its value, each member of the array will be represented in the format `key[]=value1&key[]value2`. Otherwise, the key-value pair will be formatted as "key=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 URL-encoded query string
- */
-extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
/**
`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`. See `AFHTTPClientOperation` for further details.
+ 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
@@ -107,34 +46,60 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
By default, `AFHTTPClient` sets the following HTTP headers:
- `Accept-Encoding: gzip`
- - `Accept-Language: ([NSLocale preferredLanguages]), en-us;q=0.8`
+ - `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 interract:
+ 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/
+ 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.
*/
-@interface AFHTTPClient : NSObject
+
+#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:parameteres:success:failure`
+ The url used as the base for paths specified in methods such as `getPath:parameters:success:failure`
*/
-@property (readonly, nonatomic, retain) NSURL *baseURL;
+@property (readonly, nonatomic) NSURL *baseURL;
/**
The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
@@ -151,12 +116,12 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
/**
The operation queue which manages operations enqueued by the HTTP client.
*/
-@property (readonly, nonatomic, retain) NSOperationQueue *operationQueue;
+@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).
+ @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;
@@ -195,7 +160,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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).
+ @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;
@@ -208,22 +173,18 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
/**
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
- @param The subclass of `AFHTTPRequestOperation` to register
+ @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.
-
- @see `AFHTTPClientOperation`
*/
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
/**
- Unregisters the specified subclass of `AFHTTPRequestOperation`.
-
- @param The class conforming to the `AFHTTPClientOperation` protocol to unregister
-
- @discussion After this method is invoked, `operationClass` is no longer consulted when `requestWithMethod:path:parameters` is invoked.
+ 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;
@@ -333,7 +294,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
@@ -354,7 +315,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
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 url The path to match for the cancelled requests.
+ @param path The path to match for the cancelled requests.
*/
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
@@ -372,7 +333,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
/**
@@ -383,7 +344,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
///---------------------------
@@ -396,9 +357,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
+ @see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)getPath:(NSString *)path
parameters:(NSDictionary *)parameters
@@ -411,9 +372,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
+ @see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
@@ -426,9 +387,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
+ @see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
@@ -441,9 +402,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
+ @see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)deletePath:(NSString *)path
parameters:(NSDictionary *)parameters
@@ -456,9 +417,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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 resonse 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.
+ @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
+ @see -HTTPRequestOperationWithRequest:success:failure:
*/
- (void)patchPath:(NSString *)path
parameters:(NSDictionary *)parameters
@@ -466,12 +427,99 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
@end
-#pragma mark -
+///----------------
+/// @name Constants
+///----------------
/**
- The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
+ ### 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,
+ }
- @see `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`
+ `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
@@ -481,7 +529,8 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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;
+- (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.
@@ -489,17 +538,21 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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;
+- (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`.
- @param filename The filename to be associated with the specified data. This parameter must not be `nil`.
*/
-- (void)appendPartWithFileData:(NSData *)data name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType;
+- (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.
@@ -512,7 +565,9 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
@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;
+- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
+ name:(NSString *)name
+ error:(NSError **)error;
/**
Appends encoded data to the form data.
@@ -529,4 +584,3 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
- (void)appendString:(NSString *)string;
@end
-
View
328 AFNetworking/AFHTTPClient.m
@@ -1,17 +1,17 @@
// 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
@@ -24,7 +24,6 @@
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"
-#import "AFJSONUtilities.h"
#import <Availability.h>
@@ -41,11 +40,9 @@
#import <netdb.h>
#endif
-NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
-
@interface AFMultipartFormData : NSObject <AFMultipartFormData>
-- (id)initWithURLRequest:(NSMutableURLRequest *)request
+- (id)initWithURLRequest:(NSMutableURLRequest *)request
stringEncoding:(NSStringEncoding)encoding;
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
@@ -55,6 +52,9 @@ - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
#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
@@ -63,8 +63,6 @@ - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
typedef void (^AFCompletionBlock)(void);
-static NSUInteger const kAFHTTPClientDefaultMaxConcurrentOperationCount = 4;
-
static NSString * AFBase64EncodedStringFromString(NSString *string) {
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSUInteger length = [data length];
@@ -78,7 +76,7 @@ - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
for (NSUInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
- value |= (0xFF & input[j]);
+ value |= (0xFF & input[j]);
}
}
@@ -91,114 +89,91 @@ - (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
- return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease];
+ return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
-NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
- static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+=,:;'\"`<>()[]{}/\\|~ ";
+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 [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
+ return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding));
}
#pragma mark -
-@interface AFQueryStringComponent : NSObject {
-@private
- NSString *_key;
- NSString *_value;
-}
-
-@property (readwrite, nonatomic, retain) id key;
+@interface AFQueryStringPair : NSObject
+@property (readwrite, nonatomic, retain) id field;
@property (readwrite, nonatomic, retain) id value;
-- (id)initWithKey:(id)key value:(id)value;
+- (id)initWithField:(id)field value:(id)value;
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
@end
-@implementation AFQueryStringComponent
-@synthesize key = _key;
+@implementation AFQueryStringPair
+@synthesize field = _field;
@synthesize value = _value;
-- (id)initWithKey:(id)key value:(id)value {
+- (id)initWithField:(id)field value:(id)value {
self = [super init];
if (!self) {
return nil;
}
-
- self.key = key;
+
+ self.field = field;
self.value = value;
return self;
}
-- (void)dealloc {
- [_key release];
- [_value release];
- [super dealloc];
-}
-
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
- return [NSString stringWithFormat:@"%@=%@", self.key, AFURLEncodedStringFromStringWithEncoding([self.value description], stringEncoding)];
+ return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(self.field, stringEncoding), AFPercentEscapedQueryStringPairMemberFromStringWithEncoding([self.value description], stringEncoding)];
}
@end
#pragma mark -
-extern NSArray * AFQueryStringComponentsFromKeyAndValue(NSString *key, id value);
-extern NSArray * AFQueryStringComponentsFromKeyAndDictionaryValue(NSString *key, NSDictionary *value);
-extern NSArray * AFQueryStringComponentsFromKeyAndArrayValue(NSString *key, NSArray *value);
+extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
+extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
- NSMutableArray *mutableComponents = [NSMutableArray array];
- for (AFQueryStringComponent *component in AFQueryStringComponentsFromKeyAndValue(nil, parameters)) {
- [mutableComponents addObject:[component URLEncodedStringValueWithEncoding:stringEncoding]];
+ NSMutableArray *mutablePairs = [NSMutableArray array];
+ for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
+ [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
}
- return [mutableComponents componentsJoinedByString:@"&"];
+ return [mutablePairs componentsJoinedByString:@"&"];
+}
+
+NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
+ return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
}
-NSArray * AFQueryStringComponentsFromKeyAndValue(NSString *key, id value) {
+NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
if([value isKindOfClass:[NSDictionary class]]) {
- [mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndDictionaryValue(key, value)];
+ [value enumerateKeysAndObjectsUsingBlock:^(id nestedKey, id nestedValue, BOOL *stop) {
+ [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
+ }];
} else if([value isKindOfClass:[NSArray class]]) {
- [mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndArrayValue(key, value)];
+ [value enumerateObjectsUsingBlock:^(id nestedValue, NSUInteger idx, BOOL *stop) {
+ [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
+ }];
} else {
- [mutableQueryStringComponents addObject:[[[AFQueryStringComponent alloc] initWithKey:key value:value] autorelease]];
- }
-
- return mutableQueryStringComponents;
-}
-
-NSArray * AFQueryStringComponentsFromKeyAndDictionaryValue(NSString *key, NSDictionary *value){
- NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
-
- [value enumerateKeysAndObjectsUsingBlock:^(id nestedKey, id nestedValue, BOOL *stop) {
- [mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
- }];
-
- return mutableQueryStringComponents;
-}
-
-NSArray * AFQueryStringComponentsFromKeyAndArrayValue(NSString *key, NSArray *value) {
- NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
-
- [value enumerateObjectsUsingBlock:^(id nestedValue, NSUInteger idx, BOOL *stop) {
- [mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
- }];
+ [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
+ }
return mutableQueryStringComponents;
}
static NSString * AFJSONStringFromParameters(NSDictionary *parameters) {
NSError *error = nil;
- NSData *JSONData = AFJSONEncode(parameters, &error);
+ NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];;
if (!error) {
- return [[[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding] autorelease];
+ return [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
} else {
return nil;
}
@@ -210,17 +185,17 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding
NSData *propertyListData = [NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if (!error) {
- propertyListString = [[[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] autorelease];
+ propertyListString = [[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] ;
}
return propertyListString;
}
@interface AFHTTPClient ()
-@property (readwrite, nonatomic, retain) NSURL *baseURL;
-@property (readwrite, nonatomic, retain) NSMutableArray *registeredHTTPOperationClassNames;
-@property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders;
-@property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue;
+@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;
@@ -247,7 +222,7 @@ @implementation AFHTTPClient
#endif
+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url {
- return [[[self alloc] initWithBaseURL:url] autorelease];
+ return [[self alloc] initWithBaseURL:url];
}
- (id)initWithBaseURL:(NSURL *)url {
@@ -256,6 +231,11 @@ - (id)initWithBaseURL:(NSURL *)url {
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;
@@ -264,19 +244,16 @@ - (id)initWithBaseURL:(NSURL *)url {
self.registeredHTTPOperationClassNames = [NSMutableArray array];
self.defaultHeaders = [NSMutableDictionary dictionary];
-
- // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
- [self setDefaultHeader:@"Accept-Encoding" value:@"gzip"];
- // 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]];
+ // 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:@"%@/%@ (%@, %@ %@, %@, Scale/%f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0)]];
+ [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:@"%@/%@ (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown"]];
+ [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
@@ -284,8 +261,8 @@ - (id)initWithBaseURL:(NSURL *)url {
[self startMonitoringNetworkReachability];
#endif
- self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
- [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount];
+ self.operationQueue = [[NSOperationQueue alloc] init];
+ [self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
return self;
}
@@ -293,15 +270,7 @@ - (id)initWithBaseURL:(NSURL *)url {
- (void)dealloc {
#ifdef _SYSTEMCONFIGURATION_H
[self stopMonitoringNetworkReachability];
- [_networkReachabilityStatusBlock release];
#endif
-
- [_baseURL release];
- [_registeredHTTPOperationClassNames release];
- [_defaultHeaders release];
- [_operationQueue release];
-
- [super dealloc];
}
- (NSString *)description {
@@ -339,22 +308,21 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork
return status;
}
-static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
+static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
- AFNetworkReachabilityStatusBlock block = (AFNetworkReachabilityStatusBlock)info;
+ AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info;
if (block) {
block(status);
}
- [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:[NSNumber numberWithInt:status]];
+ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]];
}
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
- return [(AFNetworkReachabilityStatusBlock)info copy];
+ return (__bridge_retained const void *)([(__bridge AFNetworkReachabilityStatusBlock)info copy]);
}
static void AFNetworkReachabilityReleaseCallback(const void *info) {
- [(AFNetworkReachabilityStatusBlock)info release];
}
- (void)startMonitoringNetworkReachability {
@@ -373,7 +341,7 @@ - (void)startMonitoringNetworkReachability {
}
};
- SCNetworkReachabilityContext context = {0, callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
+ SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
@@ -459,25 +427,26 @@ - (void)clearGeoPositionHeader {
#pragma mark -
-- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters
-{
+- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
+ path:(NSString *)path
+ parameters:(NSDictionary *)parameters
+{
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
- NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:method];
[request setAllHTTPHeaderFields:self.defaultHeaders];
+ [request setHTTPShouldHandleCookies:NO];
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"]) {
[request setHTTPShouldUsePipelining:YES];
}
- if (parameters) {
+ 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 = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
+ 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"];
@@ -504,19 +473,19 @@ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
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] autorelease];
+ __block AFMultipartFormData *formData = [[AFMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
if (parameters) {
- for (AFQueryStringComponent *component in AFQueryStringComponentsFromKeyAndValue(nil, parameters)) {
+ for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
NSData *data = nil;
- if ([component.value isKindOfClass:[NSData class]]) {
- data = component.value;
+ if ([pair.value isKindOfClass:[NSData class]]) {
+ data = pair.value;
} else {
- data = [[component.value description] dataUsingEncoding:self.stringEncoding];
+ data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
}
if (data) {
- [formData appendPartWithFormData:data name:[component.key description]];
+ [formData appendPartWithFormData:data name:[pair.field description]];
}
}
}
@@ -528,7 +497,7 @@ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
return [formData requestByFinalizingMultipartFormData];
}
-- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
+- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -538,12 +507,12 @@ - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlR
while (!operation && (className = [enumerator nextObject])) {
Class op_class = NSClassFromString(className);
if (op_class && [op_class canProcessRequest:urlRequest]) {
- operation = [[(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest] autorelease];
+ operation = [(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest];
}
}
if (!operation) {
- operation = [[[AFHTTPRequestOperation alloc] initWithRequest:urlRequest] autorelease];
+ operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
}
[operation setCompletionBlockWithSuccess:success failure:failure];
@@ -569,8 +538,8 @@ - (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)pa
}
}
-- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
+- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
NSMutableArray *mutableOperations = [NSMutableArray array];
@@ -582,8 +551,8 @@ - (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
[self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
}
-- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
+- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
+ progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
__block dispatch_group_t dispatchGroup = dispatch_group_create();
@@ -596,19 +565,24 @@ - (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
dispatch_release(dispatchGroup);
}];
- NSPredicate *finishedOperationPredicate = [NSPredicate predicateWithFormat:@"isFinished == YES"];
-
for (AFHTTPRequestOperation *operation in operations) {
- AFCompletionBlock originalCompletionBlock = [[operation.completionBlock copy] autorelease];
+ AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
operation.completionBlock = ^{
- dispatch_queue_t queue = operation.successCallbackQueue ? operation.successCallbackQueue : dispatch_get_main_queue();
+ 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([[operations filteredArrayUsingPredicate:finishedOperationPredicate] count], [operations count]);
+ progressBlock(numberOfFinishedOperations, [operations count]);
}
dispatch_group_leave(dispatchGroup);
@@ -625,8 +599,8 @@ - (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
#pragma mark -
-- (void)getPath:(NSString *)path
- parameters:(NSDictionary *)parameters
+- (void)getPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -635,8 +609,8 @@ - (void)getPath:(NSString *)path
[self enqueueHTTPRequestOperation:operation];
}
-- (void)postPath:(NSString *)path
- parameters:(NSDictionary *)parameters
+- (void)postPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -645,8 +619,8 @@ - (void)postPath:(NSString *)path
[self enqueueHTTPRequestOperation:operation];
}
-- (void)putPath:(NSString *)path
- parameters:(NSDictionary *)parameters
+- (void)putPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -655,8 +629,8 @@ - (void)putPath:(NSString *)path
[self enqueueHTTPRequestOperation:operation];
}
-- (void)deletePath:(NSString *)path
- parameters:(NSDictionary *)parameters
+- (void)deletePath:(NSString *)path
+ parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -665,8 +639,8 @@ - (void)deletePath:(NSString *)path
[self enqueueHTTPRequestOperation:operation];
}
-- (void)patchPath:(NSString *)path
- parameters:(NSDictionary *)parameters
+- (void)patchPath:(NSString *)path
+ parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
@@ -675,6 +649,47 @@ - (void)patchPath:(NSString *)path
[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 -
@@ -689,7 +704,7 @@ - (void)patchPath:(NSString *)path
NSError *error = nil;
if(![[NSFileManager defaultManager] createDirectoryAtPath:multipartTemporaryFilePath withIntermediateDirectories:YES attributes:nil error:&error]) {
- NSLog(@"Failed to create multipary temporary file directory at %@", multipartTemporaryFilePath);
+ NSLog(@"Failed to create multipart temporary file directory at %@", multipartTemporaryFilePath);
}
});
@@ -713,10 +728,10 @@ - (void)patchPath:(NSString *)path
}
@interface AFMultipartFormData ()
-@property (readwrite, nonatomic, retain) NSMutableURLRequest *request;
+@property (readwrite, nonatomic) NSMutableURLRequest *request;
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
-@property (readwrite, nonatomic, retain) NSOutputStream *outputStream;
-@property (readwrite, nonatomic, copy) NSString *temporaryFilePath;
+@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
+@property (readwrite, nonatomic, copy) NSString *temporaryFilePath;
@end
@implementation AFMultipartFormData
@@ -725,8 +740,8 @@ @implementation AFMultipartFormData
@synthesize outputStream = _outputStream;
@synthesize temporaryFilePath = _temporaryFilePath;
-- (id)initWithURLRequest:(NSMutableURLRequest *)request
- stringEncoding:(NSStringEncoding)encoding
+- (id)initWithURLRequest:(NSMutableURLRequest *)request
+ stringEncoding:(NSStringEncoding)encoding
{
self = [super init];
if (!self) {
@@ -736,7 +751,7 @@ - (id)initWithURLRequest:(NSMutableURLRequest *)request
self.request = request;
self.stringEncoding = encoding;
- self.temporaryFilePath = [AFMultipartTemporaryFileDirectoryPath() stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu", (long)[[self.request URL] hash]]];
+ self.temporaryFilePath = [AFMultipartTemporaryFileDirectoryPath() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.temporaryFilePath append:NO];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
@@ -747,16 +762,11 @@ - (id)initWithURLRequest:(NSMutableURLRequest *)request
}
- (void)dealloc {
- [_request release];
if (_outputStream) {
[_outputStream close];
- [_outputStream release];
- _outputStream = nil;
}
- [_temporaryFilePath release];
- [super dealloc];
}
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
@@ -766,7 +776,7 @@ - (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
return self.request;
}
-
+
[self appendData:[AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding]];
[self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
@@ -788,8 +798,8 @@ - (void)appendBoundary {
}
}
-- (void)appendPartWithHeaders:(NSDictionary *)headers
- body:(NSData *)body
+- (void)appendPartWithHeaders:(NSDictionary *)headers
+ body:(NSData *)body
{
[self appendBoundary];
@@ -801,8 +811,8 @@ - (void)appendPartWithHeaders:(NSDictionary *)headers
[self appendData:body];
}
-- (void)appendPartWithFormData:(NSData *)data
- name:(NSString *)name
+- (void)appendPartWithFormData:(NSData *)data
+ name:(NSString *)name
{
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
@@ -810,11 +820,11 @@ - (void)appendPartWithFormData:(NSData *)data
[self appendPartWithHeaders:mutableHeaders body:data];
}
-- (void)appendPartWithFileData:(NSData *)data
- name:(NSString *)name
- fileName:(NSString *)fileName
+- (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"];
@@ -822,16 +832,16 @@ - (void)appendPartWithFileData:(NSData *)data
[self appendPartWithHeaders:mutableHeaders body:data];
}
-- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
- name:(NSString *)name
- error:(NSError **)error
+- (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:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo] autorelease];
+ *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
}
return NO;
@@ -860,7 +870,7 @@ - (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]];
View
55 AFNetworking/AFHTTPRequestOperation.h
@@ -24,13 +24,6 @@
#import "AFURLConnectionOperation.h"
/**
- Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
- */
-extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
-
-extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
-
-/**
`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
@@ -42,31 +35,7 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
/**
The last HTTP response received by the operation's connection.
*/
-@property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
-
-/**
- Set a target file for the response, will stream directly into this destination.
- Defaults to nil, which will use a memory stream. Will create a new outputStream on change.
-
- Note: Changing this while the request is not in ready state will be ignored.
- */
-@property (nonatomic, copy) NSString *responseFilePath;
-
-
-/**
- Expected total length. This is different than expectedContentLength if the file is resumed.
- On regular requests, this is equal to self.response.expectedContentLength unless we resume a request.
-
- Note: this can also be -1 if the file size is not sent (*)
- */
-@property (assign, readonly) long long totalContentLength;
-
-/**
- Indicator for the file offset on partial/resumed downloads.
- This is greater than zero if the file download is resumed.
- */
-@property (assign, readonly) long long offsetContentLength;
-
+@property (readonly, nonatomic, strong) NSHTTPURLResponse *response;
///----------------------------------------------------------
/// @name Managing And Checking For Acceptable HTTP Responses
@@ -92,9 +61,9 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
*/
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
-///-------------------------------------------------------------
-/// @name Managing Accceptable HTTP Status Codes & Content Types
-///-------------------------------------------------------------
+///------------------------------------------------------------
+/// @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
@@ -104,7 +73,7 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
+ (NSIndexSet *)acceptableStatusCodes;
/**
- Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendents.
+ 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
*/
@@ -118,7 +87,7 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
+ (NSSet *)acceptableContentTypes;
/**
- Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendents.
+ 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
*/
@@ -144,7 +113,7 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
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 occured during 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.
*/
@@ -152,3 +121,13 @@ extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
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
165 AFNetworking/AFHTTPRequestOperation.m
@@ -23,13 +23,18 @@
#import "AFHTTPRequestOperation.h"
#import <objc/runtime.h>
-NSString * const kAFNetworkingIncompleteDownloadDirectoryName = @"Incomplete";
+// Workaround for change in imp_implementationWithBlock()
+#ifdef __IPHONE_6_0
+ #define AF_CAST_TO_BLOCK id
+#else
+ #define AF_CAST_TO_BLOCK __bridge void *
+#endif
NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
static NSCharacterSet *_skippedCharacterSet = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
- _skippedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" ,"] retain];
+ _skippedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@" ,"];
});
if (!string) {
@@ -54,11 +59,10 @@
return [NSSet setWithSet:mutableContentTypes];
}
-static void AFSwizzleClassMethodWithImplementation(Class klass, SEL selector, IMP implementation) {
+static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) {
Method originalMethod = class_getClassMethod(klass, selector);
- if (method_getImplementation(originalMethod) != implementation) {
- class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
- }
+ 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) {
@@ -91,37 +95,18 @@ static void AFSwizzleClassMethodWithImplementation(Class klass, SEL selector, IM
return string;
}
-NSString * AFCreateIncompleteDownloadDirectoryPath(void) {
- static NSString *incompleteDownloadPath;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- NSString *tempDirectory = NSTemporaryDirectory();
- incompleteDownloadPath = [[tempDirectory stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadDirectoryName] retain];
-
- NSError *error = nil;
- NSFileManager *fileMan = [[NSFileManager alloc] init];
- if(![fileMan createDirectoryAtPath:incompleteDownloadPath withIntermediateDirectories:YES attributes:nil error:&error]) {
- NSLog(@"Failed to create incomplete downloads directory at %@", incompleteDownloadPath);
- }
- [fileMan release];
- });
-
- return incompleteDownloadPath;
-}
-
#pragma mark -
@interface AFHTTPRequestOperation ()
-@property (readwrite, nonatomic, retain) NSURLRequest *request;
-@property (readwrite, nonatomic, retain) NSHTTPURLResponse *response;
-@property (readwrite, nonatomic, retain) NSError *HTTPError;
+@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 responseFilePath = _responseFilePath;
@synthesize successCallbackQueue = _successCallbackQueue;
@synthesize failureCallbackQueue = _failureCallbackQueue;
@synthesize totalContentLength = _totalContentLength;
@@ -130,8 +115,6 @@ @implementation AFHTTPRequestOperation
@dynamic response;
- (void)dealloc {
- [_HTTPError release];
-
if (_successCallbackQueue) {
dispatch_release(_successCallbackQueue);
_successCallbackQueue = NULL;
@@ -141,24 +124,28 @@ - (void)dealloc {
dispatch_release(_failureCallbackQueue);
_failureCallbackQueue = NULL;
}
-
- [super dealloc];
}
- (NSError *)error {
if (self.response && !self.HTTPError) {
- if (![self hasAcceptableStatusCode]) {
+ if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
- [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
+ [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];
- self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
- } else if ([self.responseData length] > 0 && ![self hasAcceptableContentType]) { // Don't invalidate content type if there is no content
- NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
- [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
- [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
-
- self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
+ 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];
+ }
+ }
}
}
@@ -177,7 +164,7 @@ - (void)pause {
offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
}
- NSMutableURLRequest *mutableURLRequest = [[self.request mutableCopy] autorelease];
+ NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy];
if ([[self.response allHeaderFields] valueForKey:@"ETag"]) {
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
}
@@ -188,11 +175,28 @@ - (void)pause {
}
- (BOOL)hasAcceptableStatusCode {
- return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:(NSUInteger)[self.response statusCode]];
+ 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 {
- return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:[self.response MIMEType]];
+ 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 {
@@ -226,6 +230,9 @@ - (void)setFailureCallbackQueue:(dispatch_queue_t)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;
@@ -233,49 +240,33 @@ - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operatio
if (self.error) {
if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, self.responseData);
});
}
}
};
-}
-
-- (void)setResponseFilePath:(NSString *)responseFilePath {
- if ([self isReady] && responseFilePath != _responseFilePath) {
- [_responseFilePath release];
- _responseFilePath = [responseFilePath retain];
-
- if (responseFilePath) {
- self.outputStream = [NSOutputStream outputStreamToFileAtPath:responseFilePath append:NO];
- }else {
- self.outputStream = [NSOutputStream outputStreamToMemory];
- }
- }
+#pragma clang diagnostic pop
}
#pragma mark - AFHTTPRequestOperation
-static id AFStaticClassValueImplementation(id self, SEL _cmd) {
- return objc_getAssociatedObject([self class], _cmd);
-}
-
+ (NSIndexSet *)acceptableStatusCodes {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
}
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
- NSMutableIndexSet *mutableStatusCodes = [[[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]] autorelease];
+ NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]];
[mutableStatusCodes addIndexes:statusCodes];
- SEL selector = @selector(acceptableStatusCodes);
- AFSwizzleClassMethodWithImplementation([self class], selector, (IMP)AFStaticClassValueImplementation);
- objc_setAssociatedObject([self class], selector, mutableStatusCodes, OBJC_ASSOCIATION_COPY_NONATOMIC);
+ AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(id _self) {
+ return mutableStatusCodes;
+ });
}
+ (NSSet *)acceptableContentTypes {
@@ -283,11 +274,11 @@ + (NSSet *)acceptableContentTypes {
}
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
- NSMutableSet *mutableContentTypes = [[[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES] autorelease];
+ NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES];
[mutableContentTypes unionSet:contentTypes];
- SEL selector = @selector(acceptableContentTypes);
- AFSwizzleClassMethodWithImplementation([self class], selector, (IMP)AFStaticClassValueImplementation);
- objc_setAssociatedObject([self class], selector, mutableContentTypes, OBJC_ASSOCIATION_COPY_NONATOMIC);
+ AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(id _self) {
+ return mutableContentTypes;
+ });
}
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
@@ -305,30 +296,38 @@ - (void)connection:(NSURLConnection *)connection
{
self.response = (NSHTTPURLResponse *)response;
- // 206 = Partial Content.
+ // 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;
- if ([self.response statusCode] != 206) {
+ 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];
+ }
}
}
- }else {
- NSString *contentRange = [self.response.allHeaderFields valueForKey:@"Content-Range"];
- if ([contentRange hasPrefix:@"bytes"]) {
- NSArray *bytes = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
- if ([bytes count] == 4) {
- fileOffset = [[bytes objectAtIndex:1] longLongValue];
- totalContentLength = [[bytes objectAtIndex:2] longLongValue] ?: -1; // if this is *, it's converted to 0, but -1 is default.
- }
- }
-
}
+
self.offsetContentLength = MAX(fileOffset, 0);
self.totalContentLength = totalContentLength;
+
[self.outputStream open];
}
View
8 AFNetworking/AFImageRequestOperation.h
@@ -55,23 +55,19 @@
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, retain) UIImage *responseImage;
+@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 `[[UIScreen mainScreen] scale]` by default, which automatically scales images for retina displays, for instance.
+ 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
/**
- 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.
- */
-
-/**
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.
View
28 AFNetworking/AFImageRequestOperation.m
@@ -33,7 +33,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
@interface AFImageRequestOperation ()
#if __IPHONE_OS_VERSION_MIN_REQUIRED
-@property (readwrite, nonatomic, retain) UIImage *responseImage;
+@property (readwrite, nonatomic) UIImage *responseImage;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) NSImage *responseImage;
#endif
@@ -74,7 +74,7 @@ + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)ur
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
- AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
+ AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
UIImage *image = responseObject;
@@ -82,7 +82,7 @@ + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)ur
dispatch_async(image_request_operation_processing_queue(), ^(void) {
UIImage *processedImage = imageProcessingBlock(image);
- dispatch_async(requestOperation.successCallbackQueue ? requestOperation.successCallbackQueue : dispatch_get_main_queue(), ^(void) {
+ dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
});
@@ -105,7 +105,7 @@ + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)ur
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
- AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
+ AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
NSImage *image = responseObject;
@@ -113,7 +113,7 @@ + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)ur
dispatch_async(image_request_operation_processing_queue(), ^(void) {
NSImage *processedImage = imageProcessingBlock(image);
- dispatch_async(requestOperation.successCallbackQueue ? requestOperation.successCallbackQueue : dispatch_get_main_queue(), ^(void) {
+ dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, processedImage);
});
});
@@ -144,10 +144,6 @@ - (id)initWithRequest:(NSURLRequest *)urlRequest {
return self;
}
-- (void)dealloc {
- [_responseImage release];
- [super dealloc];
-}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (UIImage *)responseImage {
@@ -177,16 +173,15 @@ - (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])] autorelease];
+ self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
[self.responseImage addRepresentation:bitimage];
- [bitimage release];
}
return _responseImage;
}
#endif
-#pragma mark - AFHTTPClientOperation
+#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];
@@ -205,6 +200,8 @@ + (BOOL)canProcessRequest:(NSURLRequest *)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;
@@ -213,7 +210,7 @@ - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operatio
dispatch_async(image_request_operation_processing_queue(), ^(void) {
if (self.error) {
if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
@@ -227,13 +224,14 @@ - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operatio
image = self.responseImage;
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, image);
});
}
}
});
- };
+ };
+#pragma clang diagnostic pop
}
@end
View
4 AFNetworking/AFJSONRequestOperation.h
@@ -44,7 +44,7 @@
/**
A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
-@property (readonly, nonatomic, retain) id responseJSON;
+@property (readonly, nonatomic) id responseJSON;
///----------------------------------
/// @name Creating Request Operations
@@ -55,7 +55,7 @@
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request.
- @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
+ @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new JSON request operation
*/
View
27 AFNetworking/AFJSONRequestOperation.m
@@ -21,7 +21,6 @@
// THE SOFTWARE.
#import "AFJSONRequestOperation.h"
-#import "AFJSONUtilities.h"
static dispatch_queue_t af_json_request_operation_processing_queue;
static dispatch_queue_t json_request_operation_processing_queue() {
@@ -33,8 +32,8 @@ static dispatch_queue_t json_request_operation_processing_queue() {
}
@interface AFJSONRequestOperation ()
-@property (readwrite, nonatomic, retain) id responseJSON;
-@property (readwrite, nonatomic, retain) NSError *JSONError;
+@property (readwrite, nonatomic) id responseJSON;
+@property (readwrite, nonatomic) NSError *JSONError;
@end
@implementation AFJSONRequestOperation
@@ -45,7 +44,7 @@ + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlR
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
- AFJSONRequestOperation *requestOperation = [[[self alloc] initWithRequest:urlRequest] autorelease];
+ AFJSONRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(operation.request, operation.response, responseObject);
@@ -59,11 +58,6 @@ + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlR
return requestOperation;
}
-- (void)dealloc {
- [_responseJSON release];
- [_JSONError release];
- [super dealloc];
-}
- (id)responseJSON {
if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
@@ -72,7 +66,7 @@ - (id)responseJSON {
if ([self.responseData length] == 0) {
self.responseJSON = nil;
} else {
- self.responseJSON = AFJSONDecode(self.responseData, &error);
+ self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error];
}
self.JSONError = error;
@@ -102,14 +96,16 @@ + (BOOL)canProcessRequest:(NSURLRequest *)request {
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
- self.completionBlock = ^ {
+#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 ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
@@ -119,20 +115,21 @@ - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operatio
if (self.JSONError) {
if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
+ dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
success(self, JSON);
});
}
}
});
}
- };
+ };
+#pragma clang diagnostic pop
}
@end
View
26 AFNetworking/AFJSONUtilities.h
@@ -1,26 +0,0 @@
-// AFJSONUtilities.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: