Merge branch 'master' into circular
BIN
media/img/originals/Twitter and Facebook buttons.psd
Normal file
BIN
media/img/originals/social-icons/16px/500px.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/16px/AddThis.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Behance.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Blogger.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Delicious.png
Normal file
After Width: | Height: | Size: 1.2 KiB |
BIN
media/img/originals/social-icons/16px/DeviantART.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Digg.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Dopplr.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/16px/Dribbble.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
media/img/originals/social-icons/16px/Evernote.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/FaceBook.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Flickr.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Forrst.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/GitHub.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Google+.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Grooveshark.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Instagram.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/16px/Lastfm.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/LinkedIn.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Mail.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/16px/MySpace.png
Normal file
After Width: | Height: | Size: 1.2 KiB |
BIN
media/img/originals/social-icons/16px/Path.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/PayPal.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Picasa.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
media/img/originals/social-icons/16px/Posterous.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/RSS.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/16px/Reddit.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/ShareThis.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Skype.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/16px/SoundCloud.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Spotify.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Stumbleupon.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Tumblr.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Twitter.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/16px/Viddler.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/16px/Vimeo.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Virb.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/16px/Windows.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/16px/WordPress.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/16px/Youtube.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/16px/Zerply.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/32px/500px.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
media/img/originals/social-icons/32px/AddThis.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
media/img/originals/social-icons/32px/Behance.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Blogger.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Deliciou.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/32px/DeviantART.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Digg.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Dopplr.png
Normal file
After Width: | Height: | Size: 1.4 KiB |
BIN
media/img/originals/social-icons/32px/Dribbble.png
Normal file
After Width: | Height: | Size: 2.8 KiB |
BIN
media/img/originals/social-icons/32px/Evernote.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
media/img/originals/social-icons/32px/Facebook.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Flickr.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Forrst.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/GitHub.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
media/img/originals/social-icons/32px/Google+.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Grooveshark.png
Normal file
After Width: | Height: | Size: 2.2 KiB |
BIN
media/img/originals/social-icons/32px/Instagram.png
Normal file
After Width: | Height: | Size: 2.9 KiB |
BIN
media/img/originals/social-icons/32px/Lastfm.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/LinkedIn.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Mail.png
Normal file
After Width: | Height: | Size: 1.8 KiB |
BIN
media/img/originals/social-icons/32px/MySpace.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
media/img/originals/social-icons/32px/Path.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Paypal.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
media/img/originals/social-icons/32px/Picasa.png
Normal file
After Width: | Height: | Size: 2.6 KiB |
BIN
media/img/originals/social-icons/32px/Posterous.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/RSS.png
Normal file
After Width: | Height: | Size: 2.4 KiB |
BIN
media/img/originals/social-icons/32px/Reddit.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/ShareThis.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
media/img/originals/social-icons/32px/Skype.png
Normal file
After Width: | Height: | Size: 2.5 KiB |
BIN
media/img/originals/social-icons/32px/Soundcloud.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
media/img/originals/social-icons/32px/Spotify.png
Normal file
After Width: | Height: | Size: 2.4 KiB |
BIN
media/img/originals/social-icons/32px/StumbleUpon.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Tumblr.png
Normal file
After Width: | Height: | Size: 1.9 KiB |
BIN
media/img/originals/social-icons/32px/Twitter.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Twitter.psd
Normal file
BIN
media/img/originals/social-icons/32px/Twitter_Off.psd
Normal file
BIN
media/img/originals/social-icons/32px/Viddler.png
Normal file
After Width: | Height: | Size: 1.6 KiB |
BIN
media/img/originals/social-icons/32px/Vimeo.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/32px/Virb.png
Normal file
After Width: | Height: | Size: 1.5 KiB |
BIN
media/img/originals/social-icons/32px/Windows.png
Normal file
After Width: | Height: | Size: 2.7 KiB |
BIN
media/img/originals/social-icons/32px/WordPress.png
Normal file
After Width: | Height: | Size: 2.6 KiB |
BIN
media/img/originals/social-icons/32px/YouTube.png
Normal file
After Width: | Height: | Size: 2 KiB |
BIN
media/img/originals/social-icons/32px/Zerply.png
Normal file
After Width: | Height: | Size: 2.1 KiB |
BIN
media/img/originals/social-icons/preview.jpg
Normal file
After Width: | Height: | Size: 78 KiB |
19
media/img/originals/social-icons/readme.txt
Normal file
|
@ -0,0 +1,19 @@
|
|||
|
||||
------------------------------------------------------------
|
||||
This resource has been created by Orman Clark for PremiumPixels.com
|
||||
------------------------------------------------------------
|
||||
|
||||
TERMS OF USE:
|
||||
|
||||
All resources made available on Premium Pixels, including but not limited to, icons, images, brushes, shapes, layer styles, layered PSDÕs, patterns, textures, web elements and themes are free for use in both personal and commercial projects.
|
||||
|
||||
You may freely use our resources, without restriction, in software programs, web templates and other materials intended for sale or distribution. No attribution or backlinks are required, but any form of spreading the word is always appreciated!
|
||||
|
||||
You are not permitted to make the resources found on Premium Pixels available for distribution elsewhere Òas isÓ without prior consent.
|
||||
|
||||
|
||||
Orman Clark for PremiumPixels.com
|
||||
_________________________
|
||||
www.premiumpixels.com
|
||||
www.ormanclark.com
|
||||
|
516
media/ios/AFNetworking/AFHTTPClient.h
Normal file
|
@ -0,0 +1,516 @@
|
|||
// 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
|
||||
|
||||
/**
|
||||
Specifies network reachability of the client to its `baseURL` domain.
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
typedef enum {
|
||||
AFNetworkReachabilityStatusUnknown = -1,
|
||||
AFNetworkReachabilityStatusNotReachable = 0,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN = 1,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
||||
} AFNetworkReachabilityStatus;
|
||||
#endif
|
||||
|
||||
/**
|
||||
Specifies the method used to encode parameters into request body.
|
||||
*/
|
||||
typedef enum {
|
||||
AFFormURLParameterEncoding,
|
||||
AFJSONParameterEncoding,
|
||||
AFPropertyListParameterEncoding,
|
||||
} AFHTTPClientParameterEncoding;
|
||||
|
||||
/**
|
||||
Returns a string, replacing certain characters with the equivalent percent escape sequence based on the specified encoding.
|
||||
|
||||
@param string The string to URL encode
|
||||
@param encoding The encoding to use for the replacement. If you are uncertain of the correct encoding, you should use UTF-8 (NSUTF8StringEncoding), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
|
||||
|
||||
@discussion The characters escaped are all characters that are not legal URL characters (based on RFC 3986), including any whitespace, punctuation, or special characters.
|
||||
|
||||
@return A URL-encoded string. If it does not need to be modified (no percent escape sequences are missing), this function may merely return string argument.
|
||||
*/
|
||||
extern NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding);
|
||||
|
||||
/**
|
||||
Returns a query string constructed by a set of parameters, using the specified encoding.
|
||||
|
||||
@param parameters The parameters used to construct the query string
|
||||
@param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (NSUTF8StringEncoding), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
|
||||
|
||||
@discussion Query strings are constructed by collecting each key-value pair, URL-encoding a string representation of the key-value pair, and then joining the components with "&".
|
||||
|
||||
|
||||
If a key-value pair has a an `NSArray` for its value, each member of the array will be represented in the format `key[]=value1&key[]value2`. Otherwise, the key-value pair will be formatted as "key=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
|
||||
|
||||
@return A URL-encoded query string
|
||||
*/
|
||||
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
|
||||
|
||||
/**
|
||||
`AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
|
||||
|
||||
## Automatic Content Parsing
|
||||
|
||||
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`. See `AFHTTPClientOperation` for further details.
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
|
||||
|
||||
## Methods to Override
|
||||
|
||||
To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
|
||||
|
||||
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
|
||||
|
||||
## Default Headers
|
||||
|
||||
By default, `AFHTTPClient` sets the following HTTP headers:
|
||||
|
||||
- `Accept-Encoding: gzip`
|
||||
- `Accept-Language: ([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
|
||||
|
||||
///---------------------------------------
|
||||
/// @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.
|
||||
|
||||
@warning JSON encoding will automatically use JSONKit, SBJSON, YAJL, or NextiveJSON, if provided. Otherwise, the built-in `NSJSONSerialization` class is used, if available (iOS 5.0 and Mac OS 10.7). If the build target does not either support `NSJSONSerialization` or include a third-party JSON library, a runtime exception will be thrown when attempting to encode parameters as JSON.
|
||||
*/
|
||||
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
|
||||
|
||||
/**
|
||||
The operation queue which manages operations enqueued by the HTTP client.
|
||||
*/
|
||||
@property (readonly, nonatomic, retain) NSOperationQueue *operationQueue;
|
||||
|
||||
/**
|
||||
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
|
||||
|
||||
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (Prefix.pch).
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
#endif
|
||||
|
||||
///---------------------------------------------
|
||||
/// @name Creating and Initializing HTTP Clients
|
||||
///---------------------------------------------
|
||||
|
||||
/**
|
||||
Creates and initializes an `AFHTTPClient` object with the specified base URL.
|
||||
|
||||
@param url The base URL for the HTTP client. This argument must not be nil.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPClient` object with the specified base URL.
|
||||
|
||||
@param url The base URL for the HTTP client. This argument must not be nil.
|
||||
|
||||
@discussion This is the designated initializer.
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (id)initWithBaseURL:(NSURL *)url;
|
||||
|
||||
///-----------------------------------
|
||||
/// @name Managing Reachability Status
|
||||
///-----------------------------------
|
||||
|
||||
/**
|
||||
Sets a callback to be executed when the network availability of the `baseURL` host changes.
|
||||
|
||||
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
|
||||
|
||||
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (Prefix.pch).
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;
|
||||
#endif
|
||||
|
||||
///-------------------------------
|
||||
/// @name Managing HTTP Operations
|
||||
///-------------------------------
|
||||
|
||||
/**
|
||||
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
|
||||
|
||||
@param 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
|
||||
|
856
media/ios/AFNetworking/AFHTTPClient.m
Normal file
|
@ -0,0 +1,856 @@
|
|||
// 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>
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
#endif
|
||||
|
||||
NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change";
|
||||
|
||||
@interface AFMultipartFormData : NSObject <AFMultipartFormData>
|
||||
|
||||
- (id)initWithURLRequest:(NSMutableURLRequest *)request
|
||||
stringEncoding:(NSStringEncoding)encoding;
|
||||
|
||||
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
typedef SCNetworkReachabilityRef AFNetworkReachabilityRef;
|
||||
typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status);
|
||||
#else
|
||||
typedef id AFNetworkReachabilityRef;
|
||||
#endif
|
||||
|
||||
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 = @"?!@#$^&%*+=,:;'\"`<>()[]{}/\\|~ ";
|
||||
|
||||
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFQueryStringComponent : NSObject {
|
||||
@private
|
||||
NSString *_key;
|
||||
NSString *_value;
|
||||
}
|
||||
|
||||
@property (readwrite, nonatomic, retain) id key;
|
||||
@property (readwrite, nonatomic, retain) id value;
|
||||
|
||||
- (id)initWithKey:(id)key value:(id)value;
|
||||
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding;
|
||||
|
||||
@end
|
||||
|
||||
@implementation AFQueryStringComponent
|
||||
@synthesize key = _key;
|
||||
@synthesize value = _value;
|
||||
|
||||
- (id)initWithKey:(id)key value:(id)value {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.key = key;
|
||||
self.value = value;
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[_key release];
|
||||
[_value release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding {
|
||||
return [NSString stringWithFormat:@"%@=%@", self.key, AFURLEncodedStringFromStringWithEncoding([self.value description], stringEncoding)];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
extern NSArray * AFQueryStringComponentsFromKeyAndValue(NSString *key, id value);
|
||||
extern NSArray * AFQueryStringComponentsFromKeyAndDictionaryValue(NSString *key, NSDictionary *value);
|
||||
extern NSArray * AFQueryStringComponentsFromKeyAndArrayValue(NSString *key, NSArray *value);
|
||||
|
||||
NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) {
|
||||
NSMutableArray *mutableComponents = [NSMutableArray array];
|
||||
for (AFQueryStringComponent *component in AFQueryStringComponentsFromKeyAndValue(nil, parameters)) {
|
||||
[mutableComponents addObject:[component URLEncodedStringValueWithEncoding:stringEncoding]];
|
||||
}
|
||||
|
||||
return [mutableComponents componentsJoinedByString:@"&"];
|
||||
}
|
||||
|
||||
NSArray * AFQueryStringComponentsFromKeyAndValue(NSString *key, id value) {
|
||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||
|
||||
if([value isKindOfClass:[NSDictionary class]]) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndDictionaryValue(key, value)];
|
||||
} else if([value isKindOfClass:[NSArray class]]) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndArrayValue(key, value)];
|
||||
} else {
|
||||
[mutableQueryStringComponents addObject:[[[AFQueryStringComponent alloc] initWithKey:key value:value] autorelease]];
|
||||
}
|
||||
|
||||
return mutableQueryStringComponents;
|
||||
}
|
||||
|
||||
NSArray * AFQueryStringComponentsFromKeyAndDictionaryValue(NSString *key, NSDictionary *value){
|
||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||
|
||||
[value enumerateKeysAndObjectsUsingBlock:^(id nestedKey, id nestedValue, BOOL *stop) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
|
||||
}];
|
||||
|
||||
return mutableQueryStringComponents;
|
||||
}
|
||||
|
||||
NSArray * AFQueryStringComponentsFromKeyAndArrayValue(NSString *key, NSArray *value) {
|
||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||
|
||||
[value enumerateObjectsUsingBlock:^(id nestedValue, NSUInteger idx, BOOL *stop) {
|
||||
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringComponentsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
|
||||
}];
|
||||
|
||||
return mutableQueryStringComponents;
|
||||
}
|
||||
|
||||
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;
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability;
|
||||
@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
|
||||
#endif
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
- (void)startMonitoringNetworkReachability;
|
||||
- (void)stopMonitoringNetworkReachability;
|
||||
#endif
|
||||
@end
|
||||
|
||||
@implementation AFHTTPClient
|
||||
@synthesize baseURL = _baseURL;
|
||||
@synthesize stringEncoding = _stringEncoding;
|
||||
@synthesize parameterEncoding = _parameterEncoding;
|
||||
@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
|
||||
@synthesize defaultHeaders = _defaultHeaders;
|
||||
@synthesize operationQueue = _operationQueue;
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
@synthesize networkReachability = _networkReachability;
|
||||
@synthesize networkReachabilityStatus = _networkReachabilityStatus;
|
||||
@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock;
|
||||
#endif
|
||||
|
||||
+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url {
|
||||
return [[[self alloc] initWithBaseURL:url] 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.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
||||
[self startMonitoringNetworkReachability];
|
||||
#endif
|
||||
|
||||
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
|
||||
[self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
[self stopMonitoringNetworkReachability];
|
||||
[_networkReachabilityStatusBlock release];
|
||||
#endif
|
||||
|
||||
[_baseURL release];
|
||||
[_registeredHTTPOperationClassNames release];
|
||||
[_defaultHeaders release];
|
||||
[_operationQueue 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 BOOL AFURLHostIsIPAddress(NSURL *url) {
|
||||
struct sockaddr_in sa_in;
|
||||
struct sockaddr_in6 sa_in6;
|
||||
|
||||
return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1);
|
||||
}
|
||||
|
||||
static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) {
|
||||
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
||||
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
||||
BOOL isNetworkReachable = (isReachable && !needsConnection);
|
||||
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
||||
if(isNetworkReachable == NO){
|
||||
status = AFNetworkReachabilityStatusNotReachable;
|
||||
}
|
||||
#if TARGET_OS_IPHONE
|
||||
else if((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0){
|
||||
status = AFNetworkReachabilityStatusReachableViaWWAN;
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
|
||||
AFNetworkReachabilityStatusBlock block = (AFNetworkReachabilityStatusBlock)info;
|
||||
if (block) {
|
||||
block(status);
|
||||
}
|
||||
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:[NSNumber numberWithInt:status]];
|
||||
}
|
||||
|
||||
static const void * AFNetworkReachabilityRetainCallback(const void *info) {
|
||||
return [(AFNetworkReachabilityStatusBlock)info copy];
|
||||
}
|
||||
|
||||
static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||
[(AFNetworkReachabilityStatusBlock)info release];
|
||||
}
|
||||
|
||||
- (void)startMonitoringNetworkReachability {
|
||||
[self stopMonitoringNetworkReachability];
|
||||
|
||||
if (!self.baseURL) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
|
||||
|
||||
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status){
|
||||
self.networkReachabilityStatus = status;
|
||||
if (self.networkReachabilityStatusBlock) {
|
||||
self.networkReachabilityStatusBlock(status);
|
||||
}
|
||||
};
|
||||
|
||||
SCNetworkReachabilityContext context = {0, callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
||||
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
|
||||
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
|
||||
|
||||
/* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered.
|
||||
*/
|
||||
if (AFURLHostIsIPAddress(self.baseURL)) {
|
||||
SCNetworkReachabilityFlags flags;
|
||||
SCNetworkReachabilityGetFlags(self.networkReachability, &flags);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags);
|
||||
callback(status);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopMonitoringNetworkReachability {
|
||||
if (_networkReachability) {
|
||||
SCNetworkReachabilityUnscheduleFromRunLoop(_networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
|
||||
CFRelease(_networkReachability);
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block {
|
||||
self.networkReachabilityStatusBlock = block;
|
||||
}
|
||||
#endif
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (BOOL)registerHTTPOperationClass:(Class)operationClass {
|
||||
if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSString *className = NSStringFromClass(operationClass);
|
||||
[self.registeredHTTPOperationClassNames removeObject:className];
|
||||
[self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)unregisterHTTPOperationClass:(Class)operationClass {
|
||||
NSString *className = NSStringFromClass(operationClass);
|
||||
[self.registeredHTTPOperationClassNames removeObject:className];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSString *)defaultValueForHeader:(NSString *)header {
|
||||
return [self.defaultHeaders valueForKey:header];
|
||||
}
|
||||
|
||||
- (void)setDefaultHeader:(NSString *)header value:(NSString *)value {
|
||||
[self.defaultHeaders setValue:value forKey:header];
|
||||
}
|
||||
|
||||
- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password {
|
||||
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
|
||||
[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]];
|
||||
}
|
||||
|
||||
- (void)setAuthorizationHeaderWithToken:(NSString *)token {
|
||||
[self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]];
|
||||
}
|
||||
|
||||
- (void)clearAuthorizationHeader {
|
||||
[self.defaultHeaders removeObjectForKey:@"Authorization"];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
||||
path:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
{
|
||||
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
|
||||
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
|
||||
[request setHTTPMethod:method];
|
||||
[request setAllHTTPHeaderFields:self.defaultHeaders];
|
||||
|
||||
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"]) {
|
||||
[request setHTTPShouldUsePipelining:YES];
|
||||
}
|
||||
|
||||
if (parameters) {
|
||||
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
|
||||
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
|
||||
[request setURL:url];
|
||||
} else {
|
||||
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
|
||||
switch (self.parameterEncoding) {
|
||||
case AFFormURLParameterEncoding:;
|
||||
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
|
||||
[request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
|
||||
break;
|
||||
case AFJSONParameterEncoding:;
|
||||
[request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
|
||||
[request setHTTPBody:[AFJSONStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
|
||||
break;
|
||||
case AFPropertyListParameterEncoding:;
|
||||
[request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
|
||||
[request setHTTPBody:[AFPropertyListStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
||||
path:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block
|
||||
{
|
||||
NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
|
||||
__block AFMultipartFormData *formData = [[[AFMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding] autorelease];
|
||||
|
||||
if (parameters) {
|
||||
for (AFQueryStringComponent *component in AFQueryStringComponentsFromKeyAndValue(nil, parameters)) {
|
||||
NSData *data = nil;
|
||||
if ([component.value isKindOfClass:[NSData class]]) {
|
||||
data = component.value;
|
||||
} else {
|
||||
data = [[component.value description] dataUsingEncoding:self.stringEncoding];
|
||||
}
|
||||
|
||||
if (data) {
|
||||
[formData appendPartWithFormData:data name:[component.key description]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (block) {
|
||||
block(formData);
|
||||
}
|
||||
|
||||
return [formData requestByFinalizingMultipartFormData];
|
||||
}
|
||||
|
||||
- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
AFHTTPRequestOperation *operation = nil;
|
||||
NSString *className = nil;
|
||||
NSEnumerator *enumerator = [self.registeredHTTPOperationClassNames reverseObjectEnumerator];
|
||||
while (!operation && (className = [enumerator nextObject])) {
|
||||
Class op_class = NSClassFromString(className);
|
||||
if (op_class && [op_class canProcessRequest:urlRequest]) {
|
||||
operation = [[(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest] 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
|
||||
{
|
||||
__block dispatch_group_t dispatchGroup = dispatch_group_create();
|
||||
NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
|
||||
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
|
||||
if (completionBlock) {
|
||||
completionBlock(operations);
|
||||
}
|
||||
});
|
||||
dispatch_release(dispatchGroup);
|
||||
}];
|
||||
|
||||
NSPredicate *finishedOperationPredicate = [NSPredicate predicateWithFormat:@"isFinished == YES"];
|
||||
|
||||
for (AFHTTPRequestOperation *operation in operations) {
|
||||
AFCompletionBlock originalCompletionBlock = [[operation.completionBlock copy] autorelease];
|
||||
operation.completionBlock = ^{
|
||||
dispatch_queue_t queue = operation.successCallbackQueue ? operation.successCallbackQueue : dispatch_get_main_queue();
|
||||
dispatch_group_async(dispatchGroup, queue, ^{
|
||||
if (originalCompletionBlock) {
|
||||
originalCompletionBlock();
|
||||
}
|
||||
|
||||
if (progressBlock) {
|
||||
progressBlock([[operations filteredArrayUsingPredicate:finishedOperationPredicate] count], [operations count]);
|
||||
}
|
||||
|
||||
dispatch_group_leave(dispatchGroup);
|
||||
});
|
||||
};
|
||||
|
||||
dispatch_group_enter(dispatchGroup);
|
||||
[batchedOperation addDependency:operation];
|
||||
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
[self.operationQueue addOperation:batchedOperation];
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
- (void)getPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
|
||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
|
||||
- (void)postPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
|
||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
|
||||
- (void)putPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
|
||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
|
||||
- (void)deletePath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
|
||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
|
||||
- (void)patchPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters];
|
||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
|
||||
[self enqueueHTTPRequestOperation:operation];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#pragma mark -
|
||||
|
||||
static NSString * const kAFMultipartTemporaryFileDirectoryName = @"com.alamofire.uploads";
|
||||
|
||||
static NSString * AFMultipartTemporaryFileDirectoryPath() {
|
||||
static NSString *multipartTemporaryFilePath = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
multipartTemporaryFilePath = [[NSTemporaryDirectory() stringByAppendingPathComponent:kAFMultipartTemporaryFileDirectoryName] copy];
|
||||
|
||||
NSError *error = nil;
|
||||
if(![[NSFileManager defaultManager] createDirectoryAtPath:multipartTemporaryFilePath withIntermediateDirectories:YES attributes:nil error:&error]) {
|
||||
NSLog(@"Failed to create multipary temporary file directory at %@", multipartTemporaryFilePath);
|
||||
}
|
||||
});
|
||||
|
||||
return multipartTemporaryFilePath;
|
||||
}
|
||||
|
||||
static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";
|
||||
|
||||
static NSString * const kAFMultipartFormCRLF = @"\r\n";
|
||||
|
||||
static inline NSString * AFMultipartFormInitialBoundary() {
|
||||
return [NSString stringWithFormat:@"--%@%@", kAFMultipartFormBoundary, kAFMultipartFormCRLF];
|
||||
}
|
||||
|
||||
static inline NSString * AFMultipartFormEncapsulationBoundary() {
|
||||
return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF];
|
||||
}
|
||||
|
||||
static inline NSString * AFMultipartFormFinalBoundary() {
|
||||
return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF];
|
||||
}
|
||||
|
||||
@interface AFMultipartFormData ()
|
||||
@property (readwrite, nonatomic, retain) NSMutableURLRequest *request;
|
||||
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
|
||||
@property (readwrite, nonatomic, retain) NSOutputStream *outputStream;
|
||||
@property (readwrite, nonatomic, copy) NSString *temporaryFilePath;
|
||||
@end
|
||||
|
||||
@implementation AFMultipartFormData
|
||||
@synthesize request = _request;
|
||||
@synthesize stringEncoding = _stringEncoding;
|
||||
@synthesize outputStream = _outputStream;
|
||||
@synthesize temporaryFilePath = _temporaryFilePath;
|
||||
|
||||
- (id)initWithURLRequest:(NSMutableURLRequest *)request
|
||||
stringEncoding:(NSStringEncoding)encoding
|
||||
{
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
self.request = request;
|
||||
self.stringEncoding = encoding;
|
||||
|
||||
self.temporaryFilePath = [AFMultipartTemporaryFileDirectoryPath() stringByAppendingPathComponent:[NSString stringWithFormat:@"%u", [[self.request URL] hash]]];
|
||||
self.outputStream = [NSOutputStream outputStreamToFileAtPath:self.temporaryFilePath append:NO];
|
||||
|
||||
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
||||
[self.outputStream scheduleInRunLoop:runLoop forMode:NSRunLoopCommonModes];
|
||||
[self.outputStream open];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[_request release];
|
||||
|
||||
if (_outputStream) {
|
||||
[_outputStream close];
|
||||
[_outputStream release];
|
||||
_outputStream = nil;
|
||||
}
|
||||
|
||||
[_temporaryFilePath release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData {
|
||||
// Close the stream and return the original request if no data has been written
|
||||
if ([[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] integerValue] == 0) {
|
||||
[self.outputStream close];
|
||||
|
||||
return self.request;
|
||||
}
|
||||
|
||||
[self appendData:[AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding]];
|
||||
|
||||
[self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
|
||||
[self.request setValue:[[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] stringValue] forHTTPHeaderField:@"Content-Length"];
|
||||
[self.request setHTTPBodyStream:[NSInputStream inputStreamWithFileAtPath:self.temporaryFilePath]];
|
||||
|
||||
[self.outputStream close];
|
||||
|
||||
return self.request;
|
||||
}
|
||||
|
||||
#pragma mark - AFMultipartFormData
|
||||
|
||||
- (void)appendBoundary {
|
||||
if ([[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] integerValue] == 0) {
|
||||
[self appendString:AFMultipartFormInitialBoundary()];
|
||||
} else {
|
||||
[self appendString:AFMultipartFormEncapsulationBoundary()];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)appendPartWithHeaders:(NSDictionary *)headers
|
||||
body:(NSData *)body
|
||||
{
|
||||
[self appendBoundary];
|
||||
|
||||
for (NSString *field in [headers allKeys]) {
|
||||
[self appendString:[NSString stringWithFormat:@"%@: %@%@", field, [headers valueForKey:field], kAFMultipartFormCRLF]];
|
||||
}
|
||||
|
||||
[self appendString:kAFMultipartFormCRLF];
|
||||
[self appendData:body];
|
||||
}
|
||||
|
||||
- (void)appendPartWithFormData:(NSData *)data
|
||||
name:(NSString *)name
|
||||
{
|
||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
|
||||
|
||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||
}
|
||||
|
||||
- (void)appendPartWithFileData:(NSData *)data
|
||||
name:(NSString *)name
|
||||
fileName:(NSString *)fileName
|
||||
mimeType:(NSString *)mimeType
|
||||
{
|
||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
||||
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
||||
|
||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||
}
|
||||
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
name:(NSString *)name
|
||||
error:(NSError **)error
|
||||
{
|
||||
if (![fileURL isFileURL]) {
|
||||
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
|
||||
[userInfo setValue:fileURL forKey:NSURLErrorFailingURLErrorKey];
|
||||
[userInfo setValue:NSLocalizedString(@"Expected URL to be a file URL", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
||||
if (error != NULL) {
|
||||
*error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo] autorelease];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL];
|
||||
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
|
||||
|
||||
NSURLResponse *response = nil;
|
||||
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
|
||||
|
||||
if (data && response) {
|
||||
[self appendPartWithFileData:data name:name fileName:[response suggestedFilename] mimeType:[response MIMEType]];
|
||||
|
||||
return YES;
|
||||
} else {
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)appendString:(NSString *)string {
|
||||
[self appendData:[string dataUsingEncoding:self.stringEncoding]];
|
||||
}
|
||||
|
||||
- (void)appendData:(NSData *)data {
|
||||
if ([data length] == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ([self.outputStream hasSpaceAvailable]) {
|
||||
const uint8_t *dataBuffer = (uint8_t *) [data bytes];
|
||||
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
154
media/ios/AFNetworking/AFHTTPRequestOperation.h
Normal file
|
@ -0,0 +1,154 @@
|
|||
// AFHTTPRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFURLConnectionOperation.h"
|
||||
|
||||
/**
|
||||
Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header.
|
||||
*/
|
||||
extern NSSet * AFContentTypesFromHTTPHeader(NSString *string);
|
||||
|
||||
extern NSString * AFCreateIncompleteDownloadDirectoryPath(void);
|
||||
|
||||
/**
|
||||
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
|
||||
*/
|
||||
@interface AFHTTPRequestOperation : AFURLConnectionOperation
|
||||
|
||||
///----------------------------------------------
|
||||
/// @name Getting HTTP URL Connection Information
|
||||
///----------------------------------------------
|
||||
|
||||
/**
|
||||
The last HTTP response received by the operation's connection.
|
||||
*/
|
||||
@property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
|
||||
|
||||
/**
|
||||
Set a target file for the response, will stream directly into this destination.
|
||||
Defaults to nil, which will use a memory stream. Will create a new outputStream on change.
|
||||
|
||||
Note: Changing this while the request is not in ready state will be ignored.
|
||||
*/
|
||||
@property (nonatomic, copy) NSString *responseFilePath;
|
||||
|
||||
|
||||
/**
|
||||
Expected total length. This is different than expectedContentLength if the file is resumed.
|
||||
On regular requests, this is equal to self.response.expectedContentLength unless we resume a request.
|
||||
|
||||
Note: this can also be -1 if the file size is not sent (*)
|
||||
*/
|
||||
@property (assign, readonly) long long totalContentLength;
|
||||
|
||||
/**
|
||||
Indicator for the file offset on partial/resumed downloads.
|
||||
This is greater than zero if the file download is resumed.
|
||||
*/
|
||||
@property (assign, readonly) long long offsetContentLength;
|
||||
|
||||
|
||||
///----------------------------------------------------------
|
||||
/// @name Managing And Checking For Acceptable HTTP Responses
|
||||
///----------------------------------------------------------
|
||||
|
||||
/**
|
||||
A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
|
||||
*/
|
||||
@property (readonly) BOOL hasAcceptableStatusCode;
|
||||
|
||||
/**
|
||||
A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
|
||||
*/
|
||||
@property (readonly) BOOL hasAcceptableContentType;
|
||||
|
||||
/**
|
||||
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
|
||||
*/
|
||||
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
|
||||
|
||||
/**
|
||||
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
|
||||
*/
|
||||
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
|
||||
|
||||
///-------------------------------------------------------------
|
||||
/// @name Managing Accceptable HTTP Status Codes & Content Types
|
||||
///-------------------------------------------------------------
|
||||
|
||||
/**
|
||||
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
|
||||
By default, this is the range 200 to 299, inclusive.
|
||||
*/
|
||||
+ (NSIndexSet *)acceptableStatusCodes;
|
||||
|
||||
/**
|
||||
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendents.
|
||||
|
||||
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
|
||||
*/
|
||||
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
|
||||
|
||||
/**
|
||||
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
|
||||
|
||||
By default, this is `nil`.
|
||||
*/
|
||||
+ (NSSet *)acceptableContentTypes;
|
||||
|
||||
/**
|
||||
Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendents.
|
||||
|
||||
@param contentTypes The content types to be added to the set of acceptable MIME types
|
||||
*/
|
||||
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes;
|
||||
|
||||
|
||||
///-----------------------------------------------------
|
||||
/// @name Determining Whether A Request Can Be Processed
|
||||
///-----------------------------------------------------
|
||||
|
||||
/**
|
||||
A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
|
||||
|
||||
@param urlRequest The request that is determined to be supported or not supported for this class.
|
||||
*/
|
||||
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
|
||||
|
||||
///-----------------------------------------------------------
|
||||
/// @name Setting Completion Block Success / Failure Callbacks
|
||||
///-----------------------------------------------------------
|
||||
|
||||
/**
|
||||
Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed.
|
||||
|
||||
@param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
|
||||
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that 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
|
335
media/ios/AFNetworking/AFHTTPRequestOperation.m
Normal file
|
@ -0,0 +1,335 @@
|
|||
// AFHTTPRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
NSString * const kAFNetworkingIncompleteDownloadDirectoryName = @"Incomplete";
|
||||
|
||||
NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
|
||||
static NSCharacterSet *_skippedCharacterSet = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_skippedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" ,"] retain];
|
||||
});
|
||||
|
||||
if (!string) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSScanner *scanner = [NSScanner scannerWithString:string];
|
||||
scanner.charactersToBeSkipped = _skippedCharacterSet;
|
||||
|
||||
NSMutableSet *mutableContentTypes = [NSMutableSet set];
|
||||
while (![scanner isAtEnd]) {
|
||||
NSString *contentType = nil;
|
||||
if ([scanner scanUpToString:@";" intoString:&contentType]) {
|
||||
[scanner scanUpToString:@"," intoString:nil];
|
||||
}
|
||||
|
||||
if (contentType) {
|
||||
[mutableContentTypes addObject:contentType];
|
||||
}
|
||||
}
|
||||
|
||||
return [NSSet setWithSet:mutableContentTypes];
|
||||
}
|
||||
|
||||
static void AFSwizzleClassMethodWithImplementation(Class klass, SEL selector, IMP implementation) {
|
||||
Method originalMethod = class_getClassMethod(klass, selector);
|
||||
if (method_getImplementation(originalMethod) != implementation) {
|
||||
class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod));
|
||||
}
|
||||
}
|
||||
|
||||
static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) {
|
||||
NSMutableString *string = [NSMutableString string];
|
||||
|
||||
NSRange range = NSMakeRange([indexSet firstIndex], 1);
|
||||
while (range.location != NSNotFound) {
|
||||
NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location];
|
||||
while (nextIndex == range.location + range.length) {
|
||||
range.length++;
|
||||
nextIndex = [indexSet indexGreaterThanIndex:nextIndex];
|
||||
}
|
||||
|
||||
if (string.length) {
|
||||
[string appendString:@","];
|
||||
}
|
||||
|
||||
if (range.length == 1) {
|
||||
[string appendFormat:@"%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;
|
||||
}
|
||||
|
||||
NSString * AFCreateIncompleteDownloadDirectoryPath(void) {
|
||||
static NSString *incompleteDownloadPath;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSString *tempDirectory = NSTemporaryDirectory();
|
||||
incompleteDownloadPath = [[tempDirectory stringByAppendingPathComponent:kAFNetworkingIncompleteDownloadDirectoryName] retain];
|
||||
|
||||
NSError *error = nil;
|
||||
NSFileManager *fileMan = [[NSFileManager alloc] init];
|
||||
if(![fileMan createDirectoryAtPath:incompleteDownloadPath withIntermediateDirectories:YES attributes:nil error:&error]) {
|
||||
NSLog(@"Failed to create incomplete downloads directory at %@", incompleteDownloadPath);
|
||||
}
|
||||
[fileMan release];
|
||||
});
|
||||
|
||||
return incompleteDownloadPath;
|
||||
}
|
||||
|
||||
#pragma mark -
|
||||
|
||||
@interface AFHTTPRequestOperation ()
|
||||
@property (readwrite, nonatomic, retain) NSURLRequest *request;
|
||||
@property (readwrite, nonatomic, retain) NSHTTPURLResponse *response;
|
||||
@property (readwrite, nonatomic, retain) NSError *HTTPError;
|
||||
@property (assign) long long totalContentLength;
|
||||
@property (assign) long long offsetContentLength;
|
||||
@end
|
||||
|
||||
@implementation AFHTTPRequestOperation
|
||||
@synthesize HTTPError = _HTTPError;
|
||||
@synthesize responseFilePath = _responseFilePath;
|
||||
@synthesize successCallbackQueue = _successCallbackQueue;
|
||||
@synthesize failureCallbackQueue = _failureCallbackQueue;
|
||||
@synthesize totalContentLength = _totalContentLength;
|
||||
@synthesize offsetContentLength = _offsetContentLength;
|
||||
@dynamic request;
|
||||
@dynamic response;
|
||||
|
||||
- (void)dealloc {
|
||||
[_HTTPError release];
|
||||
|
||||
if (_successCallbackQueue) {
|
||||
dispatch_release(_successCallbackQueue);
|
||||
_successCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
if (_failureCallbackQueue) {
|
||||
dispatch_release(_failureCallbackQueue);
|
||||
_failureCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (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 class] 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 class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
|
||||
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
|
||||
|
||||
self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
|
||||
}
|
||||
}
|
||||
|
||||
if (self.HTTPError) {
|
||||
return self.HTTPError;
|
||||
} else {
|
||||
return [super error];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)pause {
|
||||
unsigned long long offset = 0;
|
||||
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
|
||||
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
|
||||
} else {
|
||||
offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length];
|
||||
}
|
||||
|
||||
NSMutableURLRequest *mutableURLRequest = [[self.request mutableCopy] autorelease];
|
||||
if ([[self.response allHeaderFields] valueForKey:@"ETag"]) {
|
||||
[mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"];
|
||||
}
|
||||
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
|
||||
self.request = mutableURLRequest;
|
||||
|
||||
[super pause];
|
||||
}
|
||||
|
||||
- (BOOL)hasAcceptableStatusCode {
|
||||
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:[self.response statusCode]];
|
||||
}
|
||||
|
||||
- (BOOL)hasAcceptableContentType {
|
||||
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:[self.response MIMEType]];
|
||||
}
|
||||
|
||||
- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue {
|
||||
if (successCallbackQueue != _successCallbackQueue) {
|
||||
if (_successCallbackQueue) {
|
||||
dispatch_release(_successCallbackQueue);
|
||||
_successCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
if (successCallbackQueue) {
|
||||
dispatch_retain(successCallbackQueue);
|
||||
_successCallbackQueue = successCallbackQueue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
|
||||
if (failureCallbackQueue != _failureCallbackQueue) {
|
||||
if (_failureCallbackQueue) {
|
||||
dispatch_release(_failureCallbackQueue);
|
||||
_failureCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
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.responseData);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
- (void)setResponseFilePath:(NSString *)responseFilePath {
|
||||
if ([self isReady] && responseFilePath != _responseFilePath) {
|
||||
[_responseFilePath release];
|
||||
_responseFilePath = [responseFilePath retain];
|
||||
|
||||
if (responseFilePath) {
|
||||
self.outputStream = [NSOutputStream outputStreamToFileAtPath:responseFilePath append:NO];
|
||||
}else {
|
||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - AFHTTPRequestOperation
|
||||
|
||||
static id AFStaticClassValueImplementation(id self, SEL _cmd) {
|
||||
return objc_getAssociatedObject([self class], _cmd);
|
||||
}
|
||||
|
||||
+ (NSIndexSet *)acceptableStatusCodes {
|
||||
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
|
||||
}
|
||||
|
||||
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes {
|
||||
NSMutableIndexSet *mutableStatusCodes = [[[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]] autorelease];
|
||||
[mutableStatusCodes addIndexes:statusCodes];
|
||||
SEL selector = @selector(acceptableStatusCodes);
|
||||
AFSwizzleClassMethodWithImplementation([self class], selector, (IMP)AFStaticClassValueImplementation);
|
||||
objc_setAssociatedObject([self class], selector, mutableStatusCodes, OBJC_ASSOCIATION_COPY_NONATOMIC);
|
||||
}
|
||||
|
||||
+ (NSSet *)acceptableContentTypes {
|
||||
return nil;
|
||||
}
|
||||
|
||||
+ (void)addAcceptableContentTypes:(NSSet *)contentTypes {
|
||||
NSMutableSet *mutableContentTypes = [[[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES] autorelease];
|
||||
[mutableContentTypes unionSet:contentTypes];
|
||||
SEL selector = @selector(acceptableContentTypes);
|
||||
AFSwizzleClassMethodWithImplementation([self class], selector, (IMP)AFStaticClassValueImplementation);
|
||||
objc_setAssociatedObject([self class], selector, mutableContentTypes, OBJC_ASSOCIATION_COPY_NONATOMIC);
|
||||
}
|
||||
|
||||
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
|
||||
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
|
||||
}
|
||||
|
||||
#pragma mark - NSURLConnectionDelegate
|
||||
|
||||
- (void)connection:(NSURLConnection *)connection
|
||||
didReceiveResponse:(NSURLResponse *)response
|
||||
{
|
||||
self.response = (NSHTTPURLResponse *)response;
|
||||
|
||||
// 206 = Partial Content.
|
||||
long long totalContentLength = self.response.expectedContentLength;
|
||||
long long fileOffset = 0;
|
||||
if ([self.response statusCode] != 206) {
|
||||
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
|
||||
[self.outputStream setProperty:[NSNumber numberWithInteger:0] forKey:NSStreamFileCurrentOffsetKey];
|
||||
} else {
|
||||
if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) {
|
||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||
}
|
||||
}
|
||||
}else {
|
||||
NSString *contentRange = [self.response.allHeaderFields valueForKey:@"Content-Range"];
|
||||
if ([contentRange hasPrefix:@"bytes"]) {
|
||||
NSArray *bytes = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]];
|
||||
if ([bytes count] == 4) {
|
||||
fileOffset = [[bytes objectAtIndex:1] longLongValue];
|
||||
totalContentLength = [[bytes objectAtIndex:2] longLongValue] ?: -1; // if this is *, it's converted to 0, but -1 is default.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
self.offsetContentLength = MAX(fileOffset, 0);
|
||||
self.totalContentLength = totalContentLength;
|
||||
[self.outputStream open];
|
||||
}
|
||||
|
||||
@end
|
112
media/ios/AFNetworking/AFImageRequestOperation.h
Normal file
|
@ -0,0 +1,112 @@
|
|||
// AFImageRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#import <Availability.h>
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
/**
|
||||
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
|
||||
|
||||
## Acceptable Content Types
|
||||
|
||||
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
|
||||
- `image/tiff`
|
||||
- `image/jpeg`
|
||||
- `image/gif`
|
||||
- `image/png`
|
||||
- `image/ico`
|
||||
- `image/x-icon`
|
||||
- `image/bmp`
|
||||
- `image/x-bmp`
|
||||
- `image/x-xbitmap`
|
||||
- `image/x-win-bitmap`
|
||||
*/
|
||||
@interface AFImageRequestOperation : AFHTTPRequestOperation
|
||||
|
||||
/**
|
||||
An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error.
|
||||
*/
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
@property (readonly, nonatomic, 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 success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
|
||||
@param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
|
||||
|
||||
@return A new image request operation
|
||||
*/
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
|
||||
#endif
|
||||
|
||||
@end
|
236
media/ios/AFNetworking/AFImageRequestOperation.m
Normal file
|
@ -0,0 +1,236 @@
|
|||
// 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
|
||||
@end
|
||||
|
||||
@implementation AFImageRequestOperation
|
||||
@synthesize responseImage = _responseImage;
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
@synthesize imageScale = _imageScale;
|
||||
#endif
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(UIImage *image))success
|
||||
{
|
||||
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
|
||||
if (success) {
|
||||
success(image);
|
||||
}
|
||||
} failure:nil];
|
||||
}
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(NSImage *image))success
|
||||
{
|
||||
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
|
||||
if (success) {
|
||||
success(image);
|
||||
}
|
||||
} failure:nil];
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
|
||||
{
|
||||
AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
|
||||
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
if (success) {
|
||||
UIImage *image = responseObject;
|
||||
if (imageProcessingBlock) {
|
||||
dispatch_async(image_request_operation_processing_queue(), ^(void) {
|
||||
UIImage *processedImage = imageProcessingBlock(image);
|
||||
|
||||
dispatch_async(requestOperation.successCallbackQueue ? requestOperation.successCallbackQueue : dispatch_get_main_queue(), ^(void) {
|
||||
success(operation.request, operation.response, processedImage);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
success(operation.request, operation.response, image);
|
||||
}
|
||||
}
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
if (failure) {
|
||||
failure(operation.request, operation.response, error);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
|
||||
{
|
||||
AFImageRequestOperation *requestOperation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
|
||||
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
|
||||
if (success) {
|
||||
NSImage *image = responseObject;
|
||||
if (imageProcessingBlock) {
|
||||
dispatch_async(image_request_operation_processing_queue(), ^(void) {
|
||||
NSImage *processedImage = imageProcessingBlock(image);
|
||||
|
||||
dispatch_async(requestOperation.successCallbackQueue ? requestOperation.successCallbackQueue : dispatch_get_main_queue(), ^(void) {
|
||||
success(operation.request, operation.response, processedImage);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
success(operation.request, operation.response, image);
|
||||
}
|
||||
}
|
||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||
if (failure) {
|
||||
failure(operation.request, operation.response, error);
|
||||
}
|
||||
}];
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
#endif
|
||||
|
||||
- (id)initWithRequest:(NSURLRequest *)urlRequest {
|
||||
self = [super initWithRequest:urlRequest];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
self.imageScale = [[UIScreen mainScreen] scale];
|
||||
#endif
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (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;
|
||||
}
|
||||
|
||||
_imageScale = imageScale;
|
||||
|
||||
self.responseImage = nil;
|
||||
}
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
- (NSImage *)responseImage {
|
||||
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
|
||||
// Ensure that the image is set to it's correct pixel width and height
|
||||
NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData];
|
||||
self.responseImage = [[[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])] autorelease];
|
||||
[self.responseImage addRepresentation:bitimage];
|
||||
[bitimage release];
|
||||
}
|
||||
|
||||
return _responseImage;
|
||||
}
|
||||
#endif
|
||||
|
||||
#pragma mark - AFHTTPClientOperation
|
||||
|
||||
+ (NSSet *)acceptableContentTypes {
|
||||
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
|
||||
}
|
||||
|
||||
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
|
||||
static NSSet * _acceptablePathExtension = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
|
||||
});
|
||||
|
||||
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
|
||||
}
|
||||
|
||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
|
||||
{
|
||||
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) {
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
UIImage *image = nil;
|
||||
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
NSImage *image = nil;
|
||||
#endif
|
||||
|
||||
image = self.responseImage;
|
||||
|
||||
dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
|
||||
success(self, image);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
66
media/ios/AFNetworking/AFJSONRequestOperation.h
Normal file
|
@ -0,0 +1,66 @@
|
|||
// 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`
|
||||
|
||||
@warning JSON parsing will automatically use JSONKit, SBJSON, YAJL, or NextiveJSON, if provided. Otherwise, the built-in `NSJSONSerialization` class is used, if available (iOS 5.0 and Mac OS 10.7). If the build target does not either support `NSJSONSerialization` or include a third-party JSON library, a runtime exception will be thrown when attempting to parse a JSON request.
|
||||
*/
|
||||
@interface AFJSONRequestOperation : AFHTTPRequestOperation
|
||||
|
||||
///----------------------------
|
||||
/// @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
|
138
media/ios/AFNetworking/AFJSONRequestOperation.m
Normal file
|
@ -0,0 +1,138 @@
|
|||
// 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;
|
||||
@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;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[_responseJSON release];
|
||||
[_JSONError release];
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (id)responseJSON {
|
||||
if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) {
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark - AFHTTPRequestOperation
|
||||
|
||||
+ (NSSet *)acceptableContentTypes {
|
||||
return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
|
||||
}
|
||||
|
||||
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
|
||||
return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request];
|
||||
}
|
||||
|
||||
- (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(), ^{
|
||||
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
|
26
media/ios/AFNetworking/AFJSONUtilities.h
Normal file
|
@ -0,0 +1,26 @@
|
|||
// 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);
|
217
media/ios/AFNetworking/AFJSONUtilities.m
Normal file
|
@ -0,0 +1,217 @@
|
|||
// 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 _YAJLSelector = NSSelectorFromString(@"yajl_JSONString");
|
||||
|
||||
id _SBJsonWriterClass = NSClassFromString(@"SBJsonWriter");
|
||||
SEL _SBJsonWriterSelector = NSSelectorFromString(@"dataWithObject:");
|
||||
|
||||
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
|
||||
if (error != NULL) {
|
||||
[invocation setArgument:error atIndex:3];
|
||||
}
|
||||
|
||||
[invocation invoke];
|
||||
[invocation getReturnValue:&data];
|
||||
} else if (_SBJsonWriterClass && [_SBJsonWriterClass instancesRespondToSelector:_SBJsonWriterSelector]) {
|
||||
id writer = [[_SBJsonWriterClass alloc] init];
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[writer methodSignatureForSelector:_SBJsonWriterSelector]];
|
||||
invocation.target = writer;
|
||||
invocation.selector = _SBJsonWriterSelector;
|
||||
|
||||
[invocation setArgument:&object atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
|
||||
|
||||
[invocation invoke];
|
||||
[invocation getReturnValue:&data];
|
||||
[writer release];
|
||||
} 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];
|
||||
if (error != NULL) {
|
||||
[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 _YAJLSelector = NSSelectorFromString(@"yajl_JSONWithOptions:error:");
|
||||
|
||||
id _SBJSONParserClass = NSClassFromString(@"SBJsonParser");
|
||||
SEL _SBJSONParserSelector = NSSelectorFromString(@"objectWithData:");
|
||||
|
||||
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
|
||||
if (error != NULL) {
|
||||
[invocation setArgument:&error atIndex:3];
|
||||
}
|
||||
|
||||
[invocation invoke];
|
||||
[invocation getReturnValue:&JSON];
|
||||
} else if (_SBJSONParserClass && [_SBJSONParserClass instancesRespondToSelector:_SBJSONParserSelector]) {
|
||||
id parser = [[_SBJSONParserClass alloc] init];
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[parser methodSignatureForSelector:_SBJSONParserSelector]];
|
||||
invocation.target = parser;
|
||||
invocation.selector = _SBJSONParserSelector;
|
||||
|
||||
[invocation setArgument:&data atIndex:2]; // arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
|
||||
|
||||
[invocation invoke];
|
||||
[invocation getReturnValue:&JSON];
|
||||
[parser release];
|
||||
} 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
|
||||
if (error != NULL) {
|
||||
[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
|
||||
if (error != NULL) {
|
||||
[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];
|
||||
if (error != NULL) {
|
||||
[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;
|
||||
}
|
68
media/ios/AFNetworking/AFNetworkActivityIndicatorManager.h
Normal file
|
@ -0,0 +1,68 @@
|
|||
// 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.
|
||||
|
||||
@discussion By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
|
||||
*/
|
||||
@interface AFNetworkActivityIndicatorManager : NSObject
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the manager is enabled.
|
||||
|
||||
@discussion If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
|
||||
*/
|
||||
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
|
||||
|
||||
/**
|
||||
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
||||
|
||||
/**
|
||||
Returns the shared network activity indicator manager object for the system.
|
||||
|
||||
@return The systemwide network activity indicator manager.
|
||||
*/
|
||||
+ (AFNetworkActivityIndicatorManager *)sharedManager;
|
||||
|
||||
/**
|
||||
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)incrementActivityCount;
|
||||
|
||||
/**
|
||||
Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator.
|
||||
*/
|
||||
- (void)decrementActivityCount;
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
134
media/ios/AFNetworking/AFNetworkActivityIndicatorManager.m
Normal file
|
@ -0,0 +1,134 @@
|
|||
// AFNetworkActivityIndicatorManager.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 "AFNetworkActivityIndicatorManager.h"
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25;
|
||||
|
||||
@interface AFNetworkActivityIndicatorManager ()
|
||||
@property (readwrite, atomic, assign) NSInteger activityCount;
|
||||
@property (readwrite, nonatomic, retain) NSTimer *activityIndicatorVisibilityTimer;
|
||||
@property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibility;
|
||||
@end
|
||||
|
||||
@implementation AFNetworkActivityIndicatorManager
|
||||
@synthesize activityCount = _activityCount;
|
||||
@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
|
||||
@synthesize enabled = _enabled;
|
||||
@dynamic networkActivityIndicatorVisible;
|
||||
|
||||
+ (AFNetworkActivityIndicatorManager *)sharedManager {
|
||||
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
|
||||
static dispatch_once_t oncePredicate;
|
||||
dispatch_once(&oncePredicate, ^{
|
||||
_sharedManager = [[self alloc] init];
|
||||
});
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
- (id)init {
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
[_activityIndicatorVisibilityTimer invalidate];
|
||||
[_activityIndicatorVisibilityTimer release]; _activityIndicatorVisibilityTimer = nil;
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
|
||||
if (self.enabled) {
|
||||
// Delay hiding of activity indicator for a short interval, to avoid flickering
|
||||
if (![self isNetworkActivityIndicatorVisible]) {
|
||||
[self.activityIndicatorVisibilityTimer invalidate];
|
||||
self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
|
||||
[[NSRunLoop currentRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
|
||||
} else {
|
||||
[self updateNetworkActivityIndicatorVisibility];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isNetworkActivityIndicatorVisible {
|
||||
return _activityCount > 0;
|
||||
}
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibility {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
|
||||
});
|
||||
}
|
||||
|
||||
// Not exposed, but used if activityCount is set via KVC.
|
||||
- (NSInteger)activityCount {
|
||||
return _activityCount;
|
||||
}
|
||||
|
||||
- (void)setActivityCount:(NSInteger)activityCount {
|
||||
@synchronized(self) {
|
||||
_activityCount = activityCount;
|
||||
}
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
}
|
||||
|
||||
- (void)incrementActivityCount {
|
||||
[self willChangeValueForKey:@"activityCount"];
|
||||
@synchronized(self) {
|
||||
_activityCount++;
|
||||
}
|
||||
[self didChangeValueForKey:@"activityCount"];
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
}
|
||||
|
||||
- (void)decrementActivityCount {
|
||||
[self willChangeValueForKey:@"activityCount"];
|
||||
@synchronized(self) {
|
||||
_activityCount--;
|
||||
}
|
||||
[self didChangeValueForKey:@"activityCount"];
|
||||
[self updateNetworkActivityIndicatorVisibilityDelayed];
|
||||
}
|
||||
|
||||
+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible {
|
||||
return [NSSet setWithObject:@"activityCount"];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
44
media/ios/AFNetworking/AFNetworking.h
Normal file
|
@ -0,0 +1,44 @@
|
|||
// AFNetworking.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>
|
||||
|
||||
#ifndef _AFNETWORKING_
|
||||
#define _AFNETWORKING_
|
||||
|
||||
#import "AFURLConnectionOperation.h"
|
||||
|
||||
#import "AFHTTPRequestOperation.h"
|
||||
#import "AFJSONRequestOperation.h"
|
||||
#import "AFXMLRequestOperation.h"
|
||||
#import "AFPropertyListRequestOperation.h"
|
||||
#import "AFHTTPClient.h"
|
||||
|
||||
#import "AFImageRequestOperation.h"
|
||||
|
||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||
#import "AFNetworkActivityIndicatorManager.h"
|
||||
#import "UIImageView+AFNetworking.h"
|
||||
#endif
|
||||
|
||||
#endif /* _AFNETWORKING_ */
|