Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Use CocoaPod to manage libs

  • Loading branch information...
commit 3bf06c1bd9a9a349ca396a7896e1936204105ab9 1 parent d224c8d
@winfield authored
Showing with 903 additions and 5,241 deletions.
  1. +1 −0  .gitignore
  2. +0 −501 AFNetworking/AFHTTPClient.h
  3. +0 −647 AFNetworking/AFHTTPClient.m
  4. +0 −109 AFNetworking/AFHTTPRequestOperation.h
  5. +0 −190 AFNetworking/AFHTTPRequestOperation.m
  6. +0 −123 AFNetworking/AFImageRequestOperation.h
  7. +0 −249 AFNetworking/AFImageRequestOperation.m
  8. +0 −68 AFNetworking/AFJSONRequestOperation.h
  9. +0 −154 AFNetworking/AFJSONRequestOperation.m
  10. +0 −26 AFNetworking/AFJSONUtilities.h
  11. +0 −198 AFNetworking/AFJSONUtilities.m
  12. +0 −66 AFNetworking/AFNetworkActivityIndicatorManager.h
  13. +0 −114 AFNetworking/AFNetworkActivityIndicatorManager.m
  14. +0 −44 AFNetworking/AFNetworking.h
  15. +0 −74 AFNetworking/AFPropertyListRequestOperation.h
  16. +0 −154 AFNetworking/AFPropertyListRequestOperation.m
  17. +0 −214 AFNetworking/AFURLConnectionOperation.h
  18. +0 −504 AFNetworking/AFURLConnectionOperation.m
  19. +0 −96 AFNetworking/AFXMLRequestOperation.h
  20. +0 −193 AFNetworking/AFXMLRequestOperation.m
  21. +0 −75 AFNetworking/UIImageView+AFNetworking.h
  22. +0 −181 AFNetworking/UIImageView+AFNetworking.m
  23. +4 −0 Podfile
  24. +9 −0 Podfile.lock
  25. +0 −59 PullRefreshTableViewController.h
  26. +0 −181 PullRefreshTableViewController.m
  27. +889 −435 Ruby China.xcodeproj/project.pbxproj
  28. BIN  Ruby China/Default.png
  29. BIN  Ruby China/Icon.png
  30. BIN  Ruby China/Icon@2x.png
  31. BIN  SVProgressHUD/SVProgressHUD.bundle/error.png
  32. BIN  SVProgressHUD/SVProgressHUD.bundle/error@2x.png
  33. BIN  SVProgressHUD/SVProgressHUD.bundle/success.png
  34. BIN  SVProgressHUD/SVProgressHUD.bundle/success@2x.png
  35. +0 −44 SVProgressHUD/SVProgressHUD.h
  36. +0 −542 SVProgressHUD/SVProgressHUD.m
View
1  .gitignore
@@ -6,3 +6,4 @@ xcuserdata/
SharedLib
*.mode1v3
*.pbxuser
+Pods/
View
501 AFNetworking/AFHTTPClient.h
@@ -1,501 +0,0 @@
-// AFHTTPClient.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-
-@class AFHTTPRequestOperation;
-@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
-
-/**
- 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.
-
- ## Subclassing Notes
-
- In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
-
- ## Methods to Override
-
- To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
-
- To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `enqueueHTTPRequestOperationWithRequest:success:failure`.
-
- ## Default Headers
-
- By default, `AFHTTPClient` sets the following HTTP headers:
-
- - `Accept-Encoding: gzip`
- - `Accept-Language: ([NSLocale preferredLanguages]), 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:
-
- 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/
-
- */
-@interface AFHTTPClient : NSObject {
-@private
- NSURL *_baseURL;
- NSStringEncoding _stringEncoding;
- AFHTTPClientParameterEncoding _parameterEncoding;
- NSMutableArray *_registeredHTTPOperationClassNames;
- NSMutableDictionary *_defaultHeaders;
- NSOperationQueue *_operationQueue;
-}
-
-///---------------------------------------
-/// @name Accessing HTTP Client Properties
-///---------------------------------------
-
-/**
- The url used as the base for paths specified in methods such as `getPath:parameteres:success:failure`
- */
-@property (readonly, nonatomic, retain) NSURL *baseURL;
-
-/**
- The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default.
- */
-@property (nonatomic, assign) NSStringEncoding stringEncoding;
-
-/**
- The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body. This is `AFFormURLParameterEncoding` by default.
- */
-@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
-
-/**
- The operation queue which manages operations enqueued by the HTTP client.
- */
-@property (readonly, nonatomic, retain) NSOperationQueue *operationQueue;
-
-///---------------------------------------------
-/// @name Creating and Initializing HTTP Clients
-///---------------------------------------------
-
-/**
- Creates and initializes an `AFHTTPClient` object with the specified base URL.
-
- @param url The base URL for the HTTP client. This argument must not be nil.
-
- @return The newly-initialized HTTP client
- */
-+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url;
-
-/**
- Initializes an `AFHTTPClient` object with the specified base URL.
-
- @param url The base URL for the HTTP client. This argument must not be nil.
-
- @discussion This is the designated initializer.
-
- @return The newly-initialized HTTP client
- */
-- (id)initWithBaseURL:(NSURL *)url;
-
-///-----------------------------------
-/// @name Managing Reachability Status
-///-----------------------------------
-
-/**
- Sets a callback to be executed when the network availability of the `baseURL` host changes.
-
- @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument, which is `YES` if the host is available, otherwise `NO`.
-
- @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 (^)(BOOL isNetworkReachable))block;
-#endif
-
-///-------------------------------
-/// @name Managing HTTP Operations
-///-------------------------------
-
-/**
- Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
-
- @param The subclass of `AFHTTPRequestOperation` to register
-
- @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` does 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.
- */
-- (void)unregisterHTTPOperationClass:(Class)operationClass;
-
-///----------------------------------
-/// @name Managing HTTP Header Values
-///----------------------------------
-
-/**
- Returns the value for the HTTP headers set in request objects created by the HTTP client.
-
- @param header The HTTP header to return the default value for
-
- @return The default value for the HTTP header, or `nil` if unspecified
- */
-- (NSString *)defaultValueForHeader:(NSString *)header;
-
-/**
- Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
-
- @param header The HTTP header to set a default value for
- @param value The value set as default for the specified header, or `nil
- */
-- (void)setDefaultHeader:(NSString *)header value:(NSString *)value;
-
-/**
- Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.
-
- @param username The HTTP basic auth username
- @param password The HTTP basic auth password
- */
-- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password;
-
-/**
- Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.
-
- @param token The authentication token
- */
-- (void)setAuthorizationHeaderWithToken:(NSString *)token;
-
-/**
- Clears any existing value for the "Authorization" HTTP header.
- */
-- (void)clearAuthorizationHeader;
-
-///-------------------------------
-/// @name Creating Request Objects
-///-------------------------------
-
-/**
- Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
-
- If the HTTP method is `GET`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
-
- @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`.
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
-
- @return An `NSMutableURLRequest` object
- */
-- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters;
-
-/**
- Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
-
- @param method The HTTP method for the request. Must be either `POST`, `PUT`, or `DELETE`.
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
-
- @discussion The multipart form data is constructed synchronously in the specified block, so in cases where large amounts of data are being added to the request, you should consider performing this method in the background. Likewise, the form data is constructed in-memory, so it may be advantageous to instead write parts of the form data to a file and stream the request body using the `HTTPBodyStream` property of `NSURLRequest`.
-
- @warning An exception will be raised if the specified method is not `POST`, `PUT` or `DELETE`.
-
- @return An `NSMutableURLRequest` object
- */
-- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters
- constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block;
-
-///-------------------------------
-/// @name Creating HTTP Operations
-///-------------------------------
-
-/**
- Creates an `AFHTTPRequestOperation`.
-
- In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
-
- @param request The request object to be loaded asynchronously during execution of the operation.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the 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.
- */
-- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-///----------------------------------------
-/// @name Managing Enqueued HTTP Operations
-///----------------------------------------
-
-/**
- Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
-
- @param operation The HTTP request operation to be enqueued.
- */
-- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
-
-/**
- Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
-
- @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
- @param url The path to match for the cancelled requests.
- */
-- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
-
-///---------------------------------------
-/// @name Batching HTTP Request Operations
-///---------------------------------------
-
-/**
- Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
-
- @param requests The `NSURLRequest` objects used to create and enqueue operations.
- @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
- @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
-
- @discussion Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
- */
-- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock;
-
-/**
- Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
-
- @param operations The request operations used to be batched and enqueued.
- @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
- @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
- */
-- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock;
-
-///---------------------------
-/// @name Making HTTP Requests
-///---------------------------
-
-/**
- Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and appended as the query string for the request URL.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the 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.
-
- @see HTTPRequestOperationWithRequest:success:failure
- */
-- (void)getPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the 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.
-
- @see HTTPRequestOperationWithRequest:success:failure
- */
-- (void)postPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the 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.
-
- @see HTTPRequestOperationWithRequest:success:failure
- */
-- (void)putPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and 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.
-
- @see HTTPRequestOperationWithRequest:success:failure
- */
-- (void)deletePath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-/**
- Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
-
- @param path The path to be appended to the HTTP client's base URL and used as the request URL.
- @param parameters The parameters to be encoded and set in the request HTTP body.
- @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
- @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the 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.
-
- @see HTTPRequestOperationWithRequest:success:failure
- */
-- (void)patchPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-@end
-
-#pragma mark -
-
-/**
- The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
-
- @see `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`
- */
-@protocol AFMultipartFormData
-
-/**
- Appends HTTP headers, followed by the encoded data and the multipart form boundary.
-
- @param headers The HTTP headers to be appended to the form data.
- @param body The data to be encoded and appended to the form data.
- */
-- (void)appendPartWithHeaders:(NSDictionary *)headers body:(NSData *)body;
-
-/**
- Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
-
- @param data The data to be encoded and appended to the form data.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- */
-- (void)appendPartWithFormData:(NSData *)data name:(NSString *)name;
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
-
- @param data The data to be encoded and appended to the form data.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- @param 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;
-
-/**
- Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary.
-
- @param fileURL The URL corresponding to the file whose content will be appended to the form.
- @param name The name to be associated with the specified data. This parameter must not be `nil`.
- @param error If an error occurs, upon return contains an `NSError` object that describes the problem.
-
- @return `YES` if the file data was successfully appended, otherwise `NO`.
-
- @discussion The filename and MIME type for this data in the form will be automatically generated, using `NSURLResponse` `-suggestedFilename` and `-MIMEType`, respectively.
- */
-- (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name error:(NSError **)error;
-
-/**
- Appends encoded data to the form data.
-
- @param data The data to be encoded and appended to the form data.
- */
-- (void)appendData:(NSData *)data;
-
-/**
- Appends a string to the form data.
-
- @param string The string to be encoded and appended to the form data.
- */
-- (void)appendString:(NSString *)string;
-
-@end
-
View
647 AFNetworking/AFHTTPClient.m
@@ -1,647 +0,0 @@
-// AFHTTPClient.m
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-
-#import "AFHTTPClient.h"
-#import "AFHTTPRequestOperation.h"
-#import "AFJSONUtilities.h"
-
-#import <Availability.h>
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-#import <UIKit/UIKit.h>
-#endif
-
-#ifdef _SYSTEMCONFIGURATION_H
-#import <SystemConfiguration/SystemConfiguration.h>
-#endif
-
-NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
-
-static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF
-static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";
-
-@interface AFMultipartFormData : NSObject <AFMultipartFormData> {
-@private
- NSStringEncoding _stringEncoding;
- NSMutableData *_mutableData;
-}
-
-@property (readonly) NSData *data;
-
-- (id)initWithStringEncoding:(NSStringEncoding)encoding;
-
-@end
-
-#pragma mark -
-
-#ifdef _SYSTEMCONFIGURATION_H
-typedef SCNetworkReachabilityRef AFNetworkReachabilityRef;
-#else
-typedef id AFNetworkReachabilityRef;
-#endif
-
-typedef void (^AFNetworkReachabilityStatusBlock)(BOOL isNetworkReachable);
-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];
- NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
-
- uint8_t *input = (uint8_t *)[data bytes];
- uint8_t *output = (uint8_t *)[mutableData mutableBytes];
-
- for (NSUInteger i = 0; i < length; i += 3) {
- NSUInteger value = 0;
- for (NSUInteger j = i; j < (i + 3); j++) {
- value <<= 8;
- if (j < length) {
- value |= (0xFF & input[j]);
- }
- }
-
- static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
- NSUInteger idx = (i / 3) * 4;
- output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
- output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
- output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
- output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
- }
-
- return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease];
-}
-
-NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
- static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|~ ";
-
- /*
- The documentation for `CFURLCreateStringByAddingPercentEscapes` suggests that one should "pre-process" URL strings with unpredictable sequences that may already contain percent escapes. However, if the string contains an unescaped sequence with '%' appearing without an escape code (such as when representing percentages like "42%"), `stringByReplacingPercentEscapesUsingEncoding` will return `nil`. Thus, the string is only unescaped if there are no invalid percent-escaped sequences.
- */
- NSString *unescapedString = [string stringByReplacingPercentEscapesUsingEncoding:encoding];
- if (unescapedString) {
- string = unescapedString;
- }
-
- return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
-}
-
-NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding) {
- NSMutableArray *mutableParameterComponents = [NSMutableArray array];
- for (id key in [parameters allKeys]) {
- id value = [parameters valueForKey:key];
- if ([value isKindOfClass:[NSArray class]]) {
- NSString *arrayKey = AFURLEncodedStringFromStringWithEncoding([NSString stringWithFormat:@"%@[]", [key description]], encoding);
- for (id arrayValue in value) {
- NSString *component = [NSString stringWithFormat:@"%@=%@", arrayKey, AFURLEncodedStringFromStringWithEncoding([arrayValue description], encoding)];
- [mutableParameterComponents addObject:component];
- }
- } else {
- NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromStringWithEncoding([key description], encoding), AFURLEncodedStringFromStringWithEncoding([value description], encoding)];
- [mutableParameterComponents addObject:component];
- }
- }
-
- return [mutableParameterComponents componentsJoinedByString:@"&"];
-}
-
-static NSString * AFJSONStringFromParameters(NSDictionary *parameters) {
- NSError *error = nil;
- NSData *JSONData = AFJSONEncode(parameters, &error);
- if (!error) {
- return [[[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding] autorelease];
- } else {
- return nil;
- }
-}
-
-static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) {
- NSString *propertyListString = nil;
- NSError *error = nil;
-
- NSData *propertyListData = [NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
- if (!error) {
- propertyListString = [[[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] autorelease];
- }
-
- 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, assign) AFNetworkReachabilityRef networkReachability;
-@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
-
-#ifdef _SYSTEMCONFIGURATION_H
-- (void)startMonitoringNetworkReachability;
-- (void)stopMonitoringNetworkReachability;
-#endif
-@end
-
-@implementation AFHTTPClient
-@synthesize baseURL = _baseURL;
-@synthesize stringEncoding = _stringEncoding;
-@synthesize parameterEncoding = _parameterEncoding;
-@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
-@synthesize defaultHeaders = _defaultHeaders;
-@synthesize operationQueue = _operationQueue;
-@synthesize networkReachability = _networkReachability;
-@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock;
-
-+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url {
- return [[[self alloc] initWithBaseURL:url] autorelease];
-}
-
-- (id)initWithBaseURL:(NSURL *)url {
- self = [super init];
- if (!self) {
- return nil;
- }
-
- self.baseURL = url;
-
- self.stringEncoding = NSUTF8StringEncoding;
- self.parameterEncoding = AFFormURLParameterEncoding;
-
- 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]];
-
-#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)]];
-#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"]];
-#endif
-
-#ifdef _SYSTEMCONFIGURATION_H
- [self startMonitoringNetworkReachability];
-#endif
-
- self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
- [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount];
-
- return self;
-}
-
-- (void)dealloc {
-#ifdef _SYSTEMCONFIGURATION_H
- [self stopMonitoringNetworkReachability];
-#endif
-
- [_baseURL release];
- [_registeredHTTPOperationClassNames release];
- [_defaultHeaders release];
- [_operationQueue release];
- [_networkReachabilityStatusBlock release];
-
- [super dealloc];
-}
-
-- (NSString *)description {
- return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue];
-}
-
-#pragma mark -
-
-#ifdef _SYSTEMCONFIGURATION_H
-static void AFReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
- BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
- BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
- BOOL isNetworkReachable = (isReachable && !needsConnection);
-
- AFNetworkReachabilityStatusBlock block = (AFNetworkReachabilityStatusBlock)info;
- if (block) {
- block(isNetworkReachable);
- }
-
- [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:[NSNumber numberWithBool:isNetworkReachable]];
-}
-
-- (void)startMonitoringNetworkReachability {
- [self stopMonitoringNetworkReachability];
- self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
- SCNetworkReachabilityContext context = {0, self.networkReachabilityStatusBlock, NULL, NULL, NULL};
- SCNetworkReachabilitySetCallback(self.networkReachability, AFReachabilityCallback, &context);
- SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
-}
-
-- (void)stopMonitoringNetworkReachability {
- if (_networkReachability) {
- SCNetworkReachabilityUnscheduleFromRunLoop(_networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
- CFRelease(_networkReachability);
- }
-}
-
-- (void)setReachabilityStatusChangeBlock:(void (^)(BOOL isNetworkReachable))block {
- self.networkReachabilityStatusBlock = block;
- [self startMonitoringNetworkReachability];
-}
-#endif
-
-#pragma mark -
-
-- (BOOL)registerHTTPOperationClass:(Class)operationClass {
- if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
- return NO;
- }
-
- NSString *className = NSStringFromClass(operationClass);
- [self.registeredHTTPOperationClassNames removeObject:className];
- [self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
-
- return YES;
-}
-
-- (void)unregisterHTTPOperationClass:(Class)operationClass {
- NSString *className = NSStringFromClass(operationClass);
- [self.registeredHTTPOperationClassNames removeObject:className];
-}
-
-#pragma mark -
-
-- (NSString *)defaultValueForHeader:(NSString *)header {
- return [self.defaultHeaders valueForKey:header];
-}
-
-- (void)setDefaultHeader:(NSString *)header value:(NSString *)value {
- [self.defaultHeaders setValue:value forKey:header];
-}
-
-- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password {
- NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
- [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]];
-}
-
-- (void)setAuthorizationHeaderWithToken:(NSString *)token {
- [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]];
-}
-
-- (void)clearAuthorizationHeader {
- [self.defaultHeaders removeObjectForKey:@"Authorization"];
-}
-
-#pragma mark -
-
-- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters
-{
- NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
- NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
- [request setHTTPMethod:method];
- [request setAllHTTPHeaderFields:self.defaultHeaders];
-
- 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));
- switch (self.parameterEncoding) {
- case AFFormURLParameterEncoding:;
- [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
- [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
- break;
- case AFJSONParameterEncoding:;
- [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
- [request setHTTPBody:[AFJSONStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
- break;
- case AFPropertyListParameterEncoding:;
- [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
- [request setHTTPBody:[AFPropertyListStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
- break;
- }
- }
- }
-
- return request;
-}
-
-- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
- path:(NSString *)path
- parameters:(NSDictionary *)parameters
- constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block
-{
- NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
- __block AFMultipartFormData *formData = [[AFMultipartFormData alloc] initWithStringEncoding:self.stringEncoding];
-
- id key = nil;
- NSEnumerator *enumerator = [parameters keyEnumerator];
- while ((key = [enumerator nextObject])) {
- id value = [parameters valueForKey:key];
- NSData *data = nil;
-
- if ([value isKindOfClass:[NSData class]]) {
- data = value;
- } else {
- data = [[value description] dataUsingEncoding:self.stringEncoding];
- }
-
- [formData appendPartWithFormData:data name:[key description]];
- }
-
- if (block) {
- block(formData);
- }
-
- [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
- [request setHTTPBody:[formData data]];
-
- [formData autorelease];
-
- return request;
-}
-
-- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- AFHTTPRequestOperation *operation = nil;
- NSString *className = nil;
- NSEnumerator *enumerator = [self.registeredHTTPOperationClassNames reverseObjectEnumerator];
- while (!operation && (className = [enumerator nextObject])) {
- Class op_class = NSClassFromString(className);
- if (op_class && [op_class canProcessRequest:urlRequest]) {
- operation = [[(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest] autorelease];
- }
- }
-
- if (!operation) {
- operation = [[[AFHTTPRequestOperation alloc] initWithRequest:urlRequest] autorelease];
- }
-
- [operation setCompletionBlockWithSuccess:success failure:failure];
-
- return operation;
-}
-
-#pragma mark -
-
-- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
- [self.operationQueue addOperation:operation];
-}
-
-- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path {
- for (NSOperation *operation in [self.operationQueue operations]) {
- if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
- continue;
- }
-
- if ((!method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]]) && [path isEqualToString:[[[(AFHTTPRequestOperation *)operation request] URL] path]]) {
- [operation cancel];
- }
- }
-}
-
-- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock
-{
- NSMutableArray *mutableOperations = [NSMutableArray array];
- for (NSURLRequest *request in requests) {
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
- [mutableOperations addObject:operation];
- }
-
- [self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
-}
-
-- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
- progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
- completionBlock:(void (^)(NSArray *operations))completionBlock
-{
- NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
- if (completionBlock) {
- dispatch_async(dispatch_get_main_queue(), ^{
- completionBlock(operations);
- });
- }
- }];
-
- [self.operationQueue addOperation:batchedOperation];
-
- NSPredicate *finishedOperationPredicate = [NSPredicate predicateWithFormat:@"isFinished == YES"];
-
- for (AFHTTPRequestOperation *operation in operations) {
- AFCompletionBlock originalCompletionBlock = [[operation.completionBlock copy] autorelease];
- operation.completionBlock = ^{
- if (progressBlock) {
- dispatch_async(dispatch_get_main_queue(), ^{
- progressBlock([[batchedOperation.dependencies filteredArrayUsingPredicate:finishedOperationPredicate] count], [batchedOperation.dependencies count]);
- });
- }
-
- if (originalCompletionBlock) {
- originalCompletionBlock();
- }
- };
-
- [batchedOperation addDependency:operation];
- [self enqueueHTTPRequestOperation:operation];
- }
-}
-
-#pragma mark -
-
-- (void)getPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
- [self enqueueHTTPRequestOperation:operation];
-}
-
-- (void)postPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
- [self enqueueHTTPRequestOperation:operation];
-}
-
-- (void)putPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
- [self enqueueHTTPRequestOperation:operation];
-}
-
-- (void)deletePath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
- [self enqueueHTTPRequestOperation:operation];
-}
-
-- (void)patchPath:(NSString *)path
- parameters:(NSDictionary *)parameters
- success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters];
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
- [self enqueueHTTPRequestOperation:operation];
-}
-
-@end
-
-#pragma mark -
-
-static NSString * const kAFMultipartFormCRLF = @"\r\n";
-
-static inline NSString * AFMultipartFormInitialBoundary() {
- return [NSString stringWithFormat:@"--%@%@", kAFMultipartFormBoundary, kAFMultipartFormCRLF];
-}
-
-static inline NSString * AFMultipartFormEncapsulationBoundary() {
- return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF];
-}
-
-static inline NSString * AFMultipartFormFinalBoundary() {
- return [NSString stringWithFormat:@"%@--%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF, kAFMultipartFormCRLF];
-}
-
-@interface AFMultipartFormData ()
-@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
-@property (readwrite, nonatomic, retain) NSMutableData *mutableData;
-@end
-
-@implementation AFMultipartFormData
-@synthesize stringEncoding = _stringEncoding;
-@synthesize mutableData = _mutableData;
-
-- (id)initWithStringEncoding:(NSStringEncoding)encoding {
- self = [super init];
- if (!self) {
- return nil;
- }
-
- self.stringEncoding = encoding;
- self.mutableData = [NSMutableData dataWithLength:0];
-
- return self;
-}
-
-- (void)dealloc {
- [_mutableData release];
- [super dealloc];
-}
-
-- (NSData *)data {
- NSMutableData *finalizedData = [NSMutableData dataWithData:self.mutableData];
- [finalizedData appendData:[AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding]];
- return finalizedData;
-}
-
-#pragma mark - AFMultipartFormData
-
-- (void)appendPartWithHeaders:(NSDictionary *)headers body:(NSData *)body {
- if ([self.mutableData length] == 0) {
- [self appendString:AFMultipartFormInitialBoundary()];
- } else {
- [self appendString:AFMultipartFormEncapsulationBoundary()];
- }
-
- for (NSString *field in [headers allKeys]) {
- [self appendString:[NSString stringWithFormat:@"%@: %@%@", field, [headers valueForKey:field], kAFMultipartFormCRLF]];
- }
-
- [self appendString:kAFMultipartFormCRLF];
- [self appendData:body];
-}
-
-- (void)appendPartWithFormData:(NSData *)data name:(NSString *)name {
- NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
- [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
-
- [self appendPartWithHeaders:mutableHeaders body:data];
-}
-
-- (void)appendPartWithFileData:(NSData *)data name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType {
- NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
- [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
- [mutableHeaders setValue:mimeType forKey:@"Content-Type"];
-
- [self appendPartWithHeaders:mutableHeaders body:data];
-}
-
-- (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name error:(NSError **)error {
- if (![fileURL isFileURL]) {
- NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
- [userInfo setValue:fileURL forKey:NSURLErrorFailingURLErrorKey];
- [userInfo setValue:NSLocalizedString(@"Expected URL to be a file URL", nil) forKey:NSLocalizedFailureReasonErrorKey];
- if (error != NULL) {
- *error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo] autorelease];
- }
-
- return NO;
- }
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL];
- [request setCachePolicy:NSURLCacheStorageNotAllowed];
-
- NSURLResponse *response = nil;
- NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
-
- if (data && response) {
- [self appendPartWithFileData:data name:name fileName:[response suggestedFilename] mimeType:[response MIMEType]];
-
- return YES;
- } else {
- return NO;
- }
-}
-
-- (void)appendData:(NSData *)data {
- [self.mutableData appendData:data];
-}
-
-- (void)appendString:(NSString *)string {
- [self appendData:[string dataUsingEncoding:self.stringEncoding]];
-}
-
-@end
View
109 AFNetworking/AFHTTPRequestOperation.h
@@ -1,109 +0,0 @@
-// AFHTTPOperation.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-#import "AFURLConnectionOperation.h"
-
-/**
- `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
- */
-@interface AFHTTPRequestOperation : AFURLConnectionOperation {
-@private
- NSIndexSet *_acceptableStatusCodes;
- NSSet *_acceptableContentTypes;
- NSError *_HTTPError;
- dispatch_queue_t _successCallbackQueue;
- dispatch_queue_t _failureCallbackQueue;
-}
-
-///----------------------------------------------
-/// @name Getting HTTP URL Connection Information
-///----------------------------------------------
-
-/**
- The last HTTP response received by the operation's connection.
- */
-@property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
-
-
-///----------------------------------------------------------
-/// @name Managing And Checking For Acceptable HTTP Responses
-///----------------------------------------------------------
-
-/**
- Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
-
- By default, this is the range 200 to 299, inclusive.
- */
-@property (nonatomic, retain) NSIndexSet *acceptableStatusCodes;
-
-/**
- A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
- */
-@property (readonly) BOOL hasAcceptableStatusCode;
-
-/**
- Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
-
- By default, this is `nil`.
- */
-@property (nonatomic, retain) NSSet *acceptableContentTypes;
-
-/**
- A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
- */
-@property (readonly) BOOL hasAcceptableContentType;
-
-/**
- The callback dispatch queue on success. If `NULL` (default), the main queue is used.
- */
-@property (nonatomic) dispatch_queue_t successCallbackQueue;
-
-/**
- The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
- */
-@property (nonatomic) dispatch_queue_t failureCallbackQueue;
-
-
-/**
- A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
-
- @param urlRequest The request that is determined to be supported or not supported for this class.
- */
-+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
-
-///-----------------------------------------------------------
-/// @name Setting Completion Block Success / Failure Callbacks
-///-----------------------------------------------------------
-
-/**
- Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
-
- @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
- @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occured during the request.
-
- @discussion This method should be overridden in subclasses in order to specify the response object passed into the success block.
- */
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
-
-@end
View
190 AFNetworking/AFHTTPRequestOperation.m
@@ -1,190 +0,0 @@
-// AFHTTPOperation.m
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import "AFHTTPRequestOperation.h"
-
-static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
- NSMutableString *string = [NSMutableString string];
-
- NSRange range = NSMakeRange([indexSet firstIndex], 1);
- while (range.location != NSNotFound) {
- NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
- while (nextIndex == range.location + range.length) {
- range.length++;
- nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
- }
-
- if (string.length) {
- [string appendString:@","];
- }
-
- if (range.length == 1) {
- [string appendFormat:@"%u", range.location];
- } else {
- NSUInteger firstIndex = range.location;
- NSUInteger lastIndex = firstIndex + range.length - 1;
- [string appendFormat:@"%u-%u", firstIndex, lastIndex];
- }
-
- range.location = nextIndex;
- range.length = 1;
- }
-
- return string;
-}
-
-#pragma mark -
-
-@interface AFHTTPRequestOperation ()
-@property (readwrite, nonatomic, retain) NSError *HTTPError;
-@end
-
-@implementation AFHTTPRequestOperation
-@synthesize acceptableStatusCodes = _acceptableStatusCodes;
-@synthesize acceptableContentTypes = _acceptableContentTypes;
-@synthesize HTTPError = _HTTPError;
-@synthesize successCallbackQueue = _successCallbackQueue;
-@synthesize failureCallbackQueue = _failureCallbackQueue;
-
-
-- (id)initWithRequest:(NSURLRequest *)request {
- self = [super initWithRequest:request];
- if (!self) {
- return nil;
- }
-
- self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
-
- return self;
-}
-
-- (void)dealloc {
- [_acceptableStatusCodes release];
- [_acceptableContentTypes release];
- [_HTTPError release];
-
- if (_successCallbackQueue) {
- dispatch_release(_successCallbackQueue);
- _successCallbackQueue = NULL;
- }
-
- if (_failureCallbackQueue) {
- dispatch_release(_failureCallbackQueue);
- _failureCallbackQueue = NULL;
- }
-
- [super dealloc];
-}
-
-- (NSHTTPURLResponse *)response {
- return (NSHTTPURLResponse *)[super response];
-}
-
-- (NSError *)error {
- if (self.response && !self.HTTPError) {
- if (![self hasAcceptableStatusCode]) {
- NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
- [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet(self.acceptableStatusCodes), [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
- [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
-
- 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.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.HTTPError) {
- return self.HTTPError;
- } else {
- return [super error];
- }
-}
-
-- (BOOL)hasAcceptableStatusCode {
- return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]];
-}
-
-- (BOOL)hasAcceptableContentType {
- return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]];
-}
-
-- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
- if (successCallbackQueue != _successCallbackQueue) {
- if (_successCallbackQueue) {
- dispatch_release(_successCallbackQueue);
- }
-
- if (successCallbackQueue) {
- dispatch_retain(successCallbackQueue);
- _successCallbackQueue = successCallbackQueue;
- }
- }
-}
-
-- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
- if (failureCallbackQueue != _failureCallbackQueue) {
- if (_failureCallbackQueue) {
- dispatch_release(_failureCallbackQueue);
- }
-
- if (failureCallbackQueue) {
- dispatch_retain(failureCallbackQueue);
- _failureCallbackQueue = failureCallbackQueue;
- }
- }
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- self.completionBlock = ^ {
- if ([self isCancelled]) {
- return;
- }
-
- if (self.error) {
- if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
- failure(self, self.error);
- });
- }
- } else {
- if (success) {
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
- success(self, self.responseString);
- });
- }
- }
- };
-}
-
-#pragma mark - AFHTTPClientOperation
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
- return YES;
-}
-
-@end
View
123 AFNetworking/AFImageRequestOperation.h
@@ -1,123 +0,0 @@
-// AFImageRequestOperation.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-#import "AFHTTPRequestOperation.h"
-
-#import <Availability.h>
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-#import <UIKit/UIKit.h>
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-#import <Cocoa/Cocoa.h>
-#endif
-
-/**
- `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
-
- ## Acceptable Content Types
-
- By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
-
- - `image/tiff`
- - `image/jpeg`
- - `image/gif`
- - `image/png`
- - `image/ico`
- - `image/x-icon`
- - `image/bmp`
- - `image/x-bmp`
- - `image/x-xbitmap`
- - `image/x-win-bitmap`
- */
-@interface AFImageRequestOperation : AFHTTPRequestOperation {
-@private
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
- UIImage *_responseImage;
- CGFloat _imageScale;
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- NSImage *_responseImage;
-#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.
- */
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-@property (readonly, nonatomic, retain) 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.
- */
-@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.
- @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single arguments, the image created from the response data of the request.
-
- @return A new image request operation
- */
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(UIImage *image))success;
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(NSImage *image))success;
-#endif
-
-/**
- Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
-
- @param urlRequest The request object to be loaded asynchronously during execution of the operation.
- @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
- @param cacheName The cache name to be associated with the image. `AFImageCache` associates objects by URL and cache name, allowing for multiple versions of the same image to be cached.
- @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
- @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
-
- @return A new image request operation
- */
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
- cacheName:(NSString *)cacheNameOrNil
- success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
- failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
- cacheName:(NSString *)cacheNameOrNil
- success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
- failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
-#endif
-
-@end
View
249 AFNetworking/AFImageRequestOperation.m
@@ -1,249 +0,0 @@
-// AFImageRequestOperation.m
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import "AFImageRequestOperation.h"
-
-static dispatch_queue_t af_image_request_operation_processing_queue;
-static dispatch_queue_t image_request_operation_processing_queue() {
- if (af_image_request_operation_processing_queue == NULL) {
- af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
- }
-
- return af_image_request_operation_processing_queue;
-}
-
-@interface AFImageRequestOperation ()
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-@property (readwrite, nonatomic, retain) UIImage *responseImage;
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-@property (readwrite, nonatomic, retain) NSImage *responseImage;
-#endif
-
-+ (NSSet *)defaultAcceptableContentTypes;
-+ (NSSet *)defaultAcceptablePathExtensions;
-@end
-
-@implementation AFImageRequestOperation
-@synthesize responseImage = _responseImage;
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-@synthesize imageScale = _imageScale;
-#endif
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(UIImage *image))success
-{
- return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
- if (success) {
- success(image);
- }
- } failure:nil];
-}
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(NSImage *image))success
-{
- return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
- if (success) {
- success(image);
- }
- } failure:nil];
-}
-#endif
-
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
- cacheName:(NSString *)cacheNameOrNil
- 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];
- [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- UIImage *image = responseObject;
-
- if (imageProcessingBlock) {
- image = imageProcessingBlock(image);
- }
-
- success(operation.request, operation.response, image);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (failure) {
- failure(operation.request, operation.response, error);
- }
- }];
-
-
- return requestOperation;
-}
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
- imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
- cacheName:(NSString *)cacheNameOrNil
- 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];
- [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- NSImage *image = responseObject;
-
- if (imageProcessingBlock) {
- image = imageProcessingBlock(image);
- }
-
- success(operation.request, operation.response, image);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (failure) {
- failure(operation.request, operation.response, error);
- }
- }];
-
- return requestOperation;
-}
-#endif
-
-+ (NSSet *)defaultAcceptableContentTypes {
- 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];
-}
-
-+ (NSSet *)defaultAcceptablePathExtensions {
- return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
-}
-
-- (id)initWithRequest:(NSURLRequest *)urlRequest {
- self = [super initWithRequest:urlRequest];
- if (!self) {
- return nil;
- }
-
- self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
- self.imageScale = [[UIScreen mainScreen] scale];
-#endif
-
- return self;
-}
-
-- (void)dealloc {
- [_responseImage release];
- [super dealloc];
-}
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-- (UIImage *)responseImage {
- if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
- UIImage *image = [UIImage imageWithData:self.responseData];
-
- self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
- }
-
- return _responseImage;
-}
-
-- (void)setImageScale:(CGFloat)imageScale {
- if (imageScale == _imageScale) {
- return;
- }
-
- [self willChangeValueForKey:@"imageScale"];
- _imageScale = imageScale;
- [self didChangeValueForKey:@"imageScale"];
-
- self.responseImage = nil;
-}
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-- (NSImage *)responseImage {
- if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
- // Ensure that the image is set to it's correct pixel width and height
- NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
- self.responseImage = [[[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])] autorelease];
- [self.responseImage addRepresentation:bitimage];
- [bitimage release];
- }
-
- return _responseImage;
-}
-#endif
-
-#pragma mark - AFHTTPClientOperation
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
- return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
-}
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(id object))success
- failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
-{
- return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
- success(image);
- } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
- failure(response, error);
- }];
-}
-#elif __MAC_OS_X_VERSION_MIN_REQUIRED
-+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(id object))success
- failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
-{
- return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
- success(image);
- } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
- failure(response, error);
- }];
-}
-#endif
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- self.completionBlock = ^ {
- if ([self isCancelled]) {
- return;
- }
-
- dispatch_async(image_request_operation_processing_queue(), ^(void) {
- if (self.error) {
- if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
- failure(self, self.error);
- });
- }
- } else {
- if (success) {
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
- success(self, self.responseImage);
- });
- }
- }
- });
- };
-}
-
-@end
View
68 AFNetworking/AFJSONRequestOperation.h
@@ -1,68 +0,0 @@
-// AFJSONRequestOperation.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-#import "AFHTTPRequestOperation.h"
-
-/**
- `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
-
- ## Acceptable Content Types
-
- By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
-
- - `application/json`
- - `text/json`
- */
-@interface AFJSONRequestOperation : AFHTTPRequestOperation {
-@private
- id _responseJSON;
- NSError *_JSONError;
-}
-
-///----------------------------
-/// @name Getting Response Data
-///----------------------------
-
-/**
- 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;
-
-///----------------------------------
-/// @name Creating Request Operations
-///----------------------------------
-
-/**
- Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
-
- @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.
-
- @return A new JSON request operation
- */
-+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
- success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
- failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
-
-@end
View
154 AFNetworking/AFJSONRequestOperation.m
@@ -1,154 +0,0 @@
-// AFJSONRequestOperation.m
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import "AFJSONRequestOperation.h"
-#import "AFJSONUtilities.h"
-
-static dispatch_queue_t af_json_request_operation_processing_queue;
-static dispatch_queue_t json_request_operation_processing_queue() {
- if (af_json_request_operation_processing_queue == NULL) {
- af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0);
- }
-
- return af_json_request_operation_processing_queue;
-}
-
-@interface AFJSONRequestOperation ()
-@property (readwrite, nonatomic, retain) id responseJSON;
-@property (readwrite, nonatomic, retain) NSError *JSONError;
-
-+ (NSSet *)defaultAcceptableContentTypes;
-+ (NSSet *)defaultAcceptablePathExtensions;
-@end
-
-@implementation AFJSONRequestOperation
-@synthesize responseJSON = _responseJSON;
-@synthesize JSONError = _JSONError;
-
-+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
- 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];
- [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
- if (success) {
- success(operation.request, operation.response, responseObject);
- }
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- if (failure) {
- failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
- }
- }];
-
- return requestOperation;
-}
-
-+ (NSSet *)defaultAcceptableContentTypes {
- return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
-}
-
-+ (NSSet *)defaultAcceptablePathExtensions {
- return [NSSet setWithObjects:@"json", nil];
-}
-
-+ (BOOL)canProcessRequest:(NSURLRequest *)request {
- return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
-}
-
-- (id)initWithRequest:(NSURLRequest *)urlRequest {
- self = [super initWithRequest:urlRequest];
- if (!self) {
- return nil;
- }
-
- self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
-
- return self;
-}
-
-- (void)dealloc {
- [_responseJSON release];
- [_JSONError release];
- [super dealloc];
-}
-
-- (id)responseJSON {
- if (!_responseJSON && [self.responseData length] > 0 && [self isFinished]) {
- NSError *error = nil;
-
- if ([self.responseData length] == 0) {
- self.responseJSON = nil;
- } else {
- self.responseJSON = AFJSONDecode(self.responseData, &error);
- }
-
- self.JSONError = error;
- }
-
- return _responseJSON;
-}
-
-- (NSError *)error {
- if (_JSONError) {
- return _JSONError;
- } else {
- return [super error];
- }
-}
-
-- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
- failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
-{
- self.completionBlock = ^ {
- if ([self isCancelled]) {
- return;
- }
-
- if (self.error) {
- if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
- failure(self, self.error);
- });
- }
- } else {
- dispatch_async(json_request_operation_processing_queue(), ^(void) {
- id JSON = self.responseJSON;
-
- if (self.JSONError) {
- if (failure) {
- dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
- failure(self, self.error);
- });
- }
- } else {
- if (success) {
- dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
- success(self, JSON);
- });
- }
- }
- });
- }
- };
-}
-
-@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:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-
-extern NSData * AFJSONEncode(id object, NSError **error);
-extern id AFJSONDecode(NSData *data, NSError **error);
View
198 AFNetworking/AFJSONUtilities.m
@@ -1,198 +0,0 @@
-// AFJSONUtilities.m
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import "AFJSONUtilities.h"
-
-NSData * AFJSONEncode(id object, NSError **error) {
- NSData *data = nil;
-
- SEL _JSONKitSelector = NSSelectorFromString(@"JSONDataWithOptions:error:");
- SEL _SBJSONSelector = NSSelectorFromString(@"JSONRepresentation");
- SEL _YAJLSelector = NSSelectorFromString(@"yajl_JSONString");
-
- id _NXJsonSerializerClass = NSClassFromString(@"NXJsonSerializer");
- SEL _NXJsonSerializerSelector = NSSelectorFromString(@"serialize:");
-
- id _NSJSONSerializationClass = NSClassFromString(@"NSJSONSerialization");
- SEL _NSJSONSerializationSelector = NSSelectorFromString(@"dataWithJSONObject:options:error:");
-
-#ifdef _AFNETWORKING_PREFER_NSJSONSERIALIZATION_
- if (_NSJSONSerializationClass && [_NSJSONSerializationClass respondsToSelector:_NSJSONSerializationSelector]) {
- goto _af_nsjson_encode;
- }
-#endif
-
- if (_JSONKitSelector && [object respondsToSelector:_JSONKitSelector]) {
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:_JSONKitSelector]];
- invocation.target = object;
- invocation.selector = _JSONKitSelector;
-
- NSUInteger serializeOptionFlags = 0;
- [invocation setArgument:&serializeOptionFlags atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- [invocation setArgument:error atIndex:3];
-
- [invocation invoke];
- [invocation getReturnValue:&data];
- } else if (_SBJSONSelector && [object respondsToSelector:_SBJSONSelector]) {
- NSString *JSONString = nil;
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:_SBJSONSelector]];
- invocation.target = object;
- invocation.selector = _SBJSONSelector;
-
- [invocation invoke];
- [invocation getReturnValue:&JSONString];
-
- data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
- } else if (_YAJLSelector && [object respondsToSelector:_YAJLSelector]) {
- @try {
- NSString *JSONString = nil;
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[object methodSignatureForSelector:_YAJLSelector]];
- invocation.target = object;
- invocation.selector = _YAJLSelector;
-
- [invocation invoke];
- [invocation getReturnValue:&JSONString];
-
- data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
- }
- @catch (NSException *exception) {
- *error = [[[NSError alloc] initWithDomain:NSStringFromClass([exception class]) code:0 userInfo:[exception userInfo]] autorelease];
- }
- } else if (_NXJsonSerializerClass && [_NXJsonSerializerClass respondsToSelector:_NXJsonSerializerSelector]) {
- NSString *JSONString = nil;
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[_NXJsonSerializerClass methodSignatureForSelector:_NXJsonSerializerSelector]];
- invocation.target = _NXJsonSerializerClass;
- invocation.selector = _NXJsonSerializerSelector;
-
- [invocation setArgument:&object atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
-
- [invocation invoke];
- [invocation getReturnValue:&JSONString];
- data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
- } else if (_NSJSONSerializationClass && [_NSJSONSerializationClass respondsToSelector:_NSJSONSerializationSelector]) {
-#ifdef _AFNETWORKING_PREFER_NSJSONSERIALIZATION_
- _af_nsjson_encode:
-#endif
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[_NSJSONSerializationClass methodSignatureForSelector:_NSJSONSerializationSelector]];
- invocation.target = _NSJSONSerializationClass;
- invocation.selector = _NSJSONSerializationSelector;
-
- [invocation setArgument:&object atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- NSUInteger writeOptions = 0;
- [invocation setArgument:&writeOptions atIndex:3];
- [invocation setArgument:error atIndex:4];
-
- [invocation invoke];
- [invocation getReturnValue:&data];
- } else {
- NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"Please either target a platform that supports NSJSONSerialization or add one of the following libraries to your project: JSONKit, SBJSON, or YAJL", nil) forKey:NSLocalizedRecoverySuggestionErrorKey];
- [[NSException exceptionWithName:NSInternalInconsistencyException reason:NSLocalizedString(@"No JSON generation functionality available", nil) userInfo:userInfo] raise];
- }
-
- return data;
-}
-
-id AFJSONDecode(NSData *data, NSError **error) {
- id JSON = nil;
-
- SEL _JSONKitSelector = NSSelectorFromString(@"objectFromJSONDataWithParseOptions:error:");
- SEL _SBJSONSelector = NSSelectorFromString(@"JSONValue");
- SEL _YAJLSelector = NSSelectorFromString(@"yajl_JSONWithOptions:error:");
-
- id _NSJSONSerializationClass = NSClassFromString(@"NSJSONSerialization");
- SEL _NSJSONSerializationSelector = NSSelectorFromString(@"JSONObjectWithData:options:error:");
-
- id _NXJsonParserClass = NSClassFromString(@"NXJsonParser");
- SEL _NXJsonParserSelector = NSSelectorFromString(@"parseData:error:ignoreNulls:");
-
-
-#ifdef _AFNETWORKING_PREFER_NSJSONSERIALIZATION_
- if (_NSJSONSerializationClass && [_NSJSONSerializationClass respondsToSelector:_NSJSONSerializationSelector]) {
- goto _af_nsjson_decode;
- }
-#endif
-
- if (_JSONKitSelector && [data respondsToSelector:_JSONKitSelector]) {
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[data methodSignatureForSelector:_JSONKitSelector]];
- invocation.target = data;
- invocation.selector = _JSONKitSelector;
-
- NSUInteger parseOptionFlags = 0;
- [invocation setArgument:&parseOptionFlags atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- [invocation setArgument:error atIndex:3];
-
- [invocation invoke];
- [invocation getReturnValue:&JSON];
- } else if (_SBJSONSelector && [NSString instancesRespondToSelector:_SBJSONSelector]) {
- // Create a string representation of JSON, to use SBJSON -`JSONValue` category method
- NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[string methodSignatureForSelector:_SBJSONSelector]];
- invocation.target = string;
- invocation.selector = _SBJSONSelector;
-
- [invocation invoke];
- [invocation getReturnValue:&JSON];
- } else if (_YAJLSelector && [data respondsToSelector:_YAJLSelector]) {
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[data methodSignatureForSelector:_YAJLSelector]];
- invocation.target = data;
- invocation.selector = _YAJLSelector;
-
- NSUInteger yajlParserOptions = 0;
- [invocation setArgument:&yajlParserOptions atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- [invocation setArgument:error atIndex:3];
-
- [invocation invoke];
- [invocation getReturnValue:&JSON];
- } else if (_NXJsonParserClass && [_NXJsonParserClass respondsToSelector:_NXJsonParserSelector]) {
- NSNumber *nullOption = [NSNumber numberWithBool:YES];
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[_NXJsonParserClass methodSignatureForSelector:_NXJsonParserSelector]];
- invocation.target = _NXJsonParserClass;
- invocation.selector = _NXJsonParserSelector;
-
- [invocation setArgument:&data atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- [invocation setArgument:error atIndex:3];
- [invocation setArgument:&nullOption atIndex:4];
-
- [invocation invoke];
- [invocation getReturnValue:&JSON];
- } else if (_NSJSONSerializationClass && [_NSJSONSerializationClass respondsToSelector:_NSJSONSerializationSelector]) {
-#ifdef _AFNETWORKING_PREFER_NSJSONSERIALIZATION_
- _af_nsjson_decode:
-#endif
- NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[_NSJSONSerializationClass methodSignatureForSelector:_NSJSONSerializationSelector]];
- invocation.target = _NSJSONSerializationClass;
- invocation.selector = _NSJSONSerializationSelector;
-
- [invocation setArgument:&data atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
- NSUInteger readOptions = 0;
- [invocation setArgument:&readOptions atIndex:3];
- [invocation setArgument:error atIndex:4];
-
- [invocation invoke];
- [invocation getReturnValue:&JSON];
- } else {
- NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"Please either target a platform that supports NSJSONSerialization or add one of the following libraries to your project: JSONKit, SBJSON, or YAJL", nil) forKey:NSLocalizedRecoverySuggestionErrorKey];
- [[NSException exceptionWithName:NSInternalInconsistencyException reason:NSLocalizedString(@"No JSON parsing functionality available", nil) userInfo:userInfo] raise];
- }
-
- return JSON;
-}
View
66 AFNetworking/AFNetworkActivityIndicatorManager.h
@@ -1,66 +0,0 @@
-// AFNetworkActivityIndicatorManager.h
-//
-// Copyright (c) 2011 Gowalla (http://gowalla.com/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#import <Foundation/Foundation.h>
-
-#import <Availability.h>
-
-#if __IPHONE_OS_VERSION_MIN_REQUIRED
-#import <UIKit/UIKit.h>
-
-/**
- `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
- */
-@interface AFNetworkActivityIndicatorManager : NSObject {
-@private
- NSInteger _activityCount;