Whitespace formatting by Xcode re-indentation
This commit is contained in:
parent
d9da9e5c1a
commit
83da1edd13
17 changed files with 522 additions and 522 deletions
|
|
@ -1,17 +1,17 @@
|
||||||
// AFHTTPClient.h
|
// AFHTTPClient.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -26,35 +26,35 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`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.
|
`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
|
## 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`.
|
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
|
||||||
|
|
||||||
## Subclassing Notes
|
## 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.
|
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
|
## 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 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`.
|
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
|
||||||
|
|
||||||
## Default Headers
|
## Default Headers
|
||||||
|
|
||||||
By default, `AFHTTPClient` sets the following HTTP headers:
|
By default, `AFHTTPClient` sets the following HTTP headers:
|
||||||
|
|
||||||
- `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
|
- `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
|
||||||
- `User-Agent: (generated user agent)`
|
- `User-Agent: (generated user agent)`
|
||||||
|
|
||||||
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
|
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
|
||||||
|
|
||||||
## URL Construction Using Relative Paths
|
## URL Construction Using Relative Paths
|
||||||
|
|
||||||
Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
|
Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
|
||||||
|
|
||||||
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
|
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
|
||||||
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
|
[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?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/foo
|
||||||
|
|
@ -65,9 +65,9 @@
|
||||||
Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
|
Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.
|
||||||
|
|
||||||
## NSCoding / NSCopying Conformance
|
## NSCoding / NSCopying Conformance
|
||||||
|
|
||||||
`AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
|
`AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
|
||||||
|
|
||||||
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
|
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
|
||||||
- NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
|
- NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
|
||||||
*/
|
*/
|
||||||
|
|
@ -80,15 +80,15 @@ typedef enum {
|
||||||
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
||||||
} AFNetworkReachabilityStatus;
|
} AFNetworkReachabilityStatus;
|
||||||
#else
|
#else
|
||||||
#warning SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.
|
#warning SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifndef __UTTYPE__
|
#ifndef __UTTYPE__
|
||||||
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
#if __IPHONE_OS_VERSION_MIN_REQUIRED
|
||||||
#warning MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
|
#warning MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
|
||||||
#else
|
#else
|
||||||
#warning CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
|
#warning CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
typedef enum {
|
typedef enum {
|
||||||
|
|
@ -118,7 +118,7 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body. This is `AFFormURLParameterEncoding` by default.
|
The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body. This is `AFFormURLParameterEncoding` by default.
|
||||||
|
|
||||||
@warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
|
@warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
|
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
|
||||||
|
|
@ -131,7 +131,7 @@ typedef enum {
|
||||||
/**
|
/**
|
||||||
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
|
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
|
||||||
|
|
||||||
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||||
*/
|
*/
|
||||||
#ifdef _SYSTEMCONFIGURATION_H
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||||
|
|
@ -143,20 +143,20 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and initializes an `AFHTTPClient` object with the specified base URL.
|
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`.
|
@param url The base URL for the HTTP client. This argument must not be `nil`.
|
||||||
|
|
||||||
@return The newly-initialized HTTP client
|
@return The newly-initialized HTTP client
|
||||||
*/
|
*/
|
||||||
+ (instancetype)clientWithBaseURL:(NSURL *)url;
|
+ (instancetype)clientWithBaseURL:(NSURL *)url;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Initializes an `AFHTTPClient` object with the specified base 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`.
|
@param url The base URL for the HTTP client. This argument must not be `nil`.
|
||||||
|
|
||||||
@discussion This is the designated initializer.
|
@discussion This is the designated initializer.
|
||||||
|
|
||||||
@return The newly-initialized HTTP client
|
@return The newly-initialized HTTP client
|
||||||
*/
|
*/
|
||||||
- (id)initWithBaseURL:(NSURL *)url;
|
- (id)initWithBaseURL:(NSURL *)url;
|
||||||
|
|
@ -167,9 +167,9 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a callback to be executed when the network availability of the `baseURL` host changes.
|
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`.
|
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
|
||||||
|
|
||||||
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||||
*/
|
*/
|
||||||
#ifdef _SYSTEMCONFIGURATION_H
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
|
|
@ -182,11 +182,11 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
|
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
|
||||||
|
|
||||||
@param operationClass The subclass of `AFHTTPRequestOperation` to register
|
@param operationClass The subclass of `AFHTTPRequestOperation` to register
|
||||||
|
|
||||||
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
|
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
|
||||||
|
|
||||||
@discussion When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
|
@discussion When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
|
||||||
*/
|
*/
|
||||||
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
|
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
|
||||||
|
|
@ -194,7 +194,7 @@ typedef enum {
|
||||||
/**
|
/**
|
||||||
Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
|
Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called.
|
||||||
|
|
||||||
@param operationClass The subclass of `AFHTTPRequestOperation` to register
|
@param operationClass The subclass of `AFHTTPRequestOperation` to register
|
||||||
*/
|
*/
|
||||||
- (void)unregisterHTTPOperationClass:(Class)operationClass;
|
- (void)unregisterHTTPOperationClass:(Class)operationClass;
|
||||||
|
|
||||||
|
|
@ -204,16 +204,16 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Returns the value for the HTTP headers set in request objects created by the HTTP client.
|
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
|
@param header The HTTP header to return the default value for
|
||||||
|
|
||||||
@return The default value for the HTTP header, or `nil` if unspecified
|
@return The default value for the HTTP header, or `nil` if unspecified
|
||||||
*/
|
*/
|
||||||
- (NSString *)defaultValueForHeader:(NSString *)header;
|
- (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.
|
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 header The HTTP header to set a default value for
|
||||||
@param value The value set as default for the specified header, or `nil
|
@param value The value set as default for the specified header, or `nil
|
||||||
*/
|
*/
|
||||||
|
|
@ -222,7 +222,7 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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 username The HTTP basic auth username
|
||||||
@param password The HTTP basic auth password
|
@param password The HTTP basic auth password
|
||||||
*/
|
*/
|
||||||
|
|
@ -231,7 +231,7 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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
|
@param token The authentication token
|
||||||
*/
|
*/
|
||||||
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
|
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
|
||||||
|
|
@ -248,7 +248,7 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Set the default URL credential to be set for request operations.
|
Set the default URL credential to be set for request operations.
|
||||||
|
|
||||||
@param credential The URL credential
|
@param credential The URL credential
|
||||||
*/
|
*/
|
||||||
- (void)setDefaultCredential:(NSURLCredential *)credential;
|
- (void)setDefaultCredential:(NSURLCredential *)credential;
|
||||||
|
|
@ -259,29 +259,29 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
|
Creates an `NSMutableURLRequest` object with the specified HTTP method and path.
|
||||||
|
|
||||||
If the HTTP method is `GET`, `HEAD`, or `DELETE`, 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.
|
If the HTTP method is `GET`, `HEAD`, or `DELETE`, 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`. This parameter must not be `nil`.
|
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`.
|
||||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
|
@param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL.
|
||||||
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
|
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
|
||||||
|
|
||||||
@return An `NSMutableURLRequest` object
|
@return An `NSMutableURLRequest` object
|
||||||
*/
|
*/
|
||||||
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
||||||
path:(NSString *)path
|
path:(NSString *)path
|
||||||
parameters:(NSDictionary *)parameters;
|
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
|
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. This parameter must not be `GET` or `HEAD`, or `nil`.
|
@param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`.
|
||||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
@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 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.
|
@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 Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
|
@discussion Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream.
|
||||||
|
|
||||||
@return An `NSMutableURLRequest` object
|
@return An `NSMutableURLRequest` object
|
||||||
*/
|
*/
|
||||||
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
||||||
|
|
@ -295,9 +295,9 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation`.
|
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:`.
|
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 urlRequest The request object to be loaded asynchronously during execution of the operation.
|
@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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
@ -312,17 +312,17 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
|
Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
|
||||||
|
|
||||||
@param operation The HTTP request operation to be enqueued.
|
@param operation The HTTP request operation to be enqueued.
|
||||||
*/
|
*/
|
||||||
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
|
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
|
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 method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
|
||||||
@param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
|
@param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL.
|
||||||
|
|
||||||
@discussion This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
|
@discussion This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property.
|
||||||
*/
|
*/
|
||||||
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
|
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
|
||||||
|
|
@ -333,26 +333,26 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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 urlRequests The `NSURLRequest` objects used to create and enqueue operations.
|
@param urlRequests 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 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.
|
@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.
|
@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 *)urlRequests
|
- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
|
||||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||||
completionBlock:(void (^)(NSArray *operations))completionBlock;
|
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.
|
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 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 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.
|
@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
|
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
|
||||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||||
completionBlock:(void (^)(NSArray *operations))completionBlock;
|
completionBlock:(void (^)(NSArray *operations))completionBlock;
|
||||||
|
|
||||||
///---------------------------
|
///---------------------------
|
||||||
|
|
@ -361,12 +361,12 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue.
|
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 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||||
*/
|
*/
|
||||||
- (void)getPath:(NSString *)path
|
- (void)getPath:(NSString *)path
|
||||||
|
|
@ -376,61 +376,61 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
|
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 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||||
*/
|
*/
|
||||||
- (void)postPath:(NSString *)path
|
- (void)postPath:(NSString *)path
|
||||||
parameters:(NSDictionary *)parameters
|
parameters:(NSDictionary *)parameters
|
||||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
|
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 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||||
*/
|
*/
|
||||||
- (void)putPath:(NSString *)path
|
- (void)putPath:(NSString *)path
|
||||||
parameters:(NSDictionary *)parameters
|
parameters:(NSDictionary *)parameters
|
||||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
|
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 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||||
*/
|
*/
|
||||||
- (void)deletePath:(NSString *)path
|
- (void)deletePath:(NSString *)path
|
||||||
parameters:(NSDictionary *)parameters
|
parameters:(NSDictionary *)parameters
|
||||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
|
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 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 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 success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||||
*/
|
*/
|
||||||
- (void)patchPath:(NSString *)path
|
- (void)patchPath:(NSString *)path
|
||||||
parameters:(NSDictionary *)parameters
|
parameters:(NSDictionary *)parameters
|
||||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||||
@end
|
@end
|
||||||
|
|
@ -441,54 +441,54 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
### Network Reachability
|
### Network Reachability
|
||||||
|
|
||||||
The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
|
The following constants are provided by `AFHTTPClient` as possible network reachability statuses.
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
AFNetworkReachabilityStatusUnknown,
|
AFNetworkReachabilityStatusUnknown,
|
||||||
AFNetworkReachabilityStatusNotReachable,
|
AFNetworkReachabilityStatusNotReachable,
|
||||||
AFNetworkReachabilityStatusReachableViaWWAN,
|
AFNetworkReachabilityStatusReachableViaWWAN,
|
||||||
AFNetworkReachabilityStatusReachableViaWiFi,
|
AFNetworkReachabilityStatusReachableViaWiFi,
|
||||||
}
|
}
|
||||||
|
|
||||||
`AFNetworkReachabilityStatusUnknown`
|
`AFNetworkReachabilityStatusUnknown`
|
||||||
The `baseURL` host reachability is not known.
|
The `baseURL` host reachability is not known.
|
||||||
|
|
||||||
`AFNetworkReachabilityStatusNotReachable`
|
`AFNetworkReachabilityStatusNotReachable`
|
||||||
The `baseURL` host cannot be reached.
|
The `baseURL` host cannot be reached.
|
||||||
|
|
||||||
`AFNetworkReachabilityStatusReachableViaWWAN`
|
`AFNetworkReachabilityStatusReachableViaWWAN`
|
||||||
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
|
The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.
|
||||||
|
|
||||||
`AFNetworkReachabilityStatusReachableViaWiFi`
|
`AFNetworkReachabilityStatusReachableViaWiFi`
|
||||||
The `baseURL` host can be reached via a Wi-Fi connection.
|
The `baseURL` host can be reached via a Wi-Fi connection.
|
||||||
|
|
||||||
### Keys for Notification UserInfo Dictionary
|
### Keys for Notification UserInfo Dictionary
|
||||||
|
|
||||||
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
||||||
|
|
||||||
`AFNetworkingReachabilityNotificationStatusItem`
|
`AFNetworkingReachabilityNotificationStatusItem`
|
||||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||||
|
|
||||||
### Parameter Encoding
|
### Parameter Encoding
|
||||||
|
|
||||||
The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
|
The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
|
||||||
|
|
||||||
enum {
|
enum {
|
||||||
AFFormURLParameterEncoding,
|
AFFormURLParameterEncoding,
|
||||||
AFJSONParameterEncoding,
|
AFJSONParameterEncoding,
|
||||||
AFPropertyListParameterEncoding,
|
AFPropertyListParameterEncoding,
|
||||||
}
|
}
|
||||||
|
|
||||||
`AFFormURLParameterEncoding`
|
`AFFormURLParameterEncoding`
|
||||||
Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
|
Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information.
|
||||||
|
|
||||||
`AFJSONParameterEncoding`
|
`AFJSONParameterEncoding`
|
||||||
Parameters are encoded into JSON in the message body.
|
Parameters are encoded into JSON in the message body.
|
||||||
|
|
||||||
`AFPropertyListParameterEncoding`
|
`AFPropertyListParameterEncoding`
|
||||||
Parameters are encoded into a property list in the message body.
|
Parameters are encoded into a property list in the message body.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
///----------------
|
///----------------
|
||||||
|
|
@ -497,14 +497,14 @@ typedef enum {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Returns a query string constructed by a set of parameters, using the specified 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 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.
|
@param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
|
||||||
|
|
||||||
@discussion Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
|
@discussion Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
|
||||||
|
|
||||||
If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
|
If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
|
||||||
|
|
||||||
@return A percent-escaped query string
|
@return A percent-escaped query string
|
||||||
*/
|
*/
|
||||||
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
|
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
|
||||||
|
|
@ -516,7 +516,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
|
||||||
/**
|
/**
|
||||||
Posted when network reachability changes.
|
Posted when network reachability changes.
|
||||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||||
|
|
||||||
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
@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
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
|
|
@ -536,13 +536,13 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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. This parameter must not be `nil`.
|
@param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`.
|
||||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
@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.
|
@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`.
|
@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.
|
@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
|
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||||
|
|
@ -551,7 +551,7 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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 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 name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||||
@param filename The filename to be associated with the specified data. This parameter must not be `nil`.
|
@param filename The filename to be associated with the specified data. This parameter must not be `nil`.
|
||||||
|
|
@ -564,7 +564,7 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary.
|
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 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 name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||||
*/
|
*/
|
||||||
|
|
@ -574,7 +574,7 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
|
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 headers The HTTP headers to be appended to the form data.
|
||||||
@param body The data to be encoded and appended to the form data.
|
@param body The data to be encoded and appended to the form data.
|
||||||
*/
|
*/
|
||||||
|
|
@ -583,10 +583,10 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
|
Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.
|
||||||
|
|
||||||
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
|
@param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb.
|
||||||
@param delay Duration of delay each time a packet is read. By default, no delay is set.
|
@param delay Duration of delay each time a packet is read. By default, no delay is set.
|
||||||
|
|
||||||
@discussion When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
@discussion When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.
|
||||||
*/
|
*/
|
||||||
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
|
- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes
|
||||||
|
|
|
||||||
|
|
@ -28,15 +28,15 @@
|
||||||
#import <Availability.h>
|
#import <Availability.h>
|
||||||
|
|
||||||
#ifdef _SYSTEMCONFIGURATION_H
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
#import <netinet/in.h>
|
#import <netinet/in.h>
|
||||||
#import <netinet6/in6.h>
|
#import <netinet6/in6.h>
|
||||||
#import <arpa/inet.h>
|
#import <arpa/inet.h>
|
||||||
#import <ifaddrs.h>
|
#import <ifaddrs.h>
|
||||||
#import <netdb.h>
|
#import <netdb.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
#import <UIKit/UIKit.h>
|
#import <UIKit/UIKit.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef _SYSTEMCONFIGURATION_H
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
|
|
@ -55,10 +55,10 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) {
|
||||||
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
|
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
|
||||||
NSUInteger length = [data length];
|
NSUInteger length = [data length];
|
||||||
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
|
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
|
||||||
|
|
||||||
uint8_t *input = (uint8_t *)[data bytes];
|
uint8_t *input = (uint8_t *)[data bytes];
|
||||||
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
|
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
|
||||||
|
|
||||||
for (NSUInteger i = 0; i < length; i += 3) {
|
for (NSUInteger i = 0; i < length; i += 3) {
|
||||||
NSUInteger value = 0;
|
NSUInteger value = 0;
|
||||||
for (NSUInteger j = i; j < (i + 3); j++) {
|
for (NSUInteger j = i; j < (i + 3); j++) {
|
||||||
|
|
@ -67,23 +67,23 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) {
|
||||||
value |= (0xFF & input[j]);
|
value |= (0xFF & input[j]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
NSUInteger idx = (i / 3) * 4;
|
NSUInteger idx = (i / 3) * 4;
|
||||||
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
|
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
|
||||||
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
|
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
|
||||||
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
|
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
|
||||||
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
|
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
|
||||||
}
|
}
|
||||||
|
|
||||||
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
|
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
|
||||||
}
|
}
|
||||||
|
|
||||||
static NSString * AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
|
static NSString * AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
|
||||||
static NSString * const kAFCharactersToBeEscaped = @":/?&=;+!@#$()~'";
|
static NSString * const kAFCharactersToBeEscaped = @":/?&=;+!@#$()~'";
|
||||||
static NSString * const kAFCharactersToLeaveUnescaped = @"[].";
|
static NSString * const kAFCharactersToLeaveUnescaped = @"[].";
|
||||||
|
|
||||||
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescaped, (__bridge CFStringRef)kAFCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding));
|
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescaped, (__bridge CFStringRef)kAFCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -107,10 +107,10 @@ static NSString * AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NS
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.field = field;
|
self.field = field;
|
||||||
self.value = value;
|
self.value = value;
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -134,7 +134,7 @@ NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSS
|
||||||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||||
[mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
|
[mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [mutablePairs componentsJoinedByString:@"&"];
|
return [mutablePairs componentsJoinedByString:@"&"];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -144,7 +144,7 @@ NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
|
||||||
|
|
||||||
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||||
|
|
||||||
if ([value isKindOfClass:[NSDictionary class]]) {
|
if ([value isKindOfClass:[NSDictionary class]]) {
|
||||||
// Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
|
// Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
|
||||||
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)];
|
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)];
|
||||||
|
|
@ -162,7 +162,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||||
} else {
|
} else {
|
||||||
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
|
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
|
||||||
}
|
}
|
||||||
|
|
||||||
return mutableQueryStringComponents;
|
return mutableQueryStringComponents;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -213,45 +213,45 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||||
|
|
||||||
- (id)initWithBaseURL:(NSURL *)url {
|
- (id)initWithBaseURL:(NSURL *)url {
|
||||||
NSParameterAssert(url);
|
NSParameterAssert(url);
|
||||||
|
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
|
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
|
||||||
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
|
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
|
||||||
url = [url URLByAppendingPathComponent:@""];
|
url = [url URLByAppendingPathComponent:@""];
|
||||||
}
|
}
|
||||||
|
|
||||||
self.baseURL = url;
|
self.baseURL = url;
|
||||||
|
|
||||||
self.stringEncoding = NSUTF8StringEncoding;
|
self.stringEncoding = NSUTF8StringEncoding;
|
||||||
self.parameterEncoding = AFFormURLParameterEncoding;
|
self.parameterEncoding = AFFormURLParameterEncoding;
|
||||||
|
|
||||||
self.registeredHTTPOperationClassNames = [NSMutableArray array];
|
self.registeredHTTPOperationClassNames = [NSMutableArray array];
|
||||||
|
|
||||||
self.defaultHeaders = [NSMutableDictionary dictionary];
|
self.defaultHeaders = [NSMutableDictionary dictionary];
|
||||||
|
|
||||||
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
|
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
|
||||||
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
|
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
|
||||||
[self setDefaultHeader:@"Accept-Language" value:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes]];
|
[self setDefaultHeader:@"Accept-Language" value:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes]];
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
|
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
|
||||||
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]];
|
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]];
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]];
|
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]];
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef _SYSTEMCONFIGURATION_H
|
#ifdef _SYSTEMCONFIGURATION_H
|
||||||
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
||||||
[self startMonitoringNetworkReachability];
|
[self startMonitoringNetworkReachability];
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
self.operationQueue = [[NSOperationQueue alloc] init];
|
self.operationQueue = [[NSOperationQueue alloc] init];
|
||||||
[self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
|
[self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -271,7 +271,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||||
static BOOL AFURLHostIsIPAddress(NSURL *url) {
|
static BOOL AFURLHostIsIPAddress(NSURL *url) {
|
||||||
struct sockaddr_in sa_in;
|
struct sockaddr_in sa_in;
|
||||||
struct sockaddr_in6 sa_in6;
|
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);
|
return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -279,7 +279,7 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork
|
||||||
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
||||||
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
||||||
BOOL isNetworkReachable = (isReachable && !needsConnection);
|
BOOL isNetworkReachable = (isReachable && !needsConnection);
|
||||||
|
|
||||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
||||||
if (isNetworkReachable == NO) {
|
if (isNetworkReachable == NO) {
|
||||||
status = AFNetworkReachabilityStatusNotReachable;
|
status = AFNetworkReachabilityStatusNotReachable;
|
||||||
|
|
@ -292,7 +292,7 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork
|
||||||
else {
|
else {
|
||||||
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
||||||
}
|
}
|
||||||
|
|
||||||
return status;
|
return status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -302,7 +302,7 @@ static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused targ
|
||||||
if (block) {
|
if (block) {
|
||||||
block(status);
|
block(status);
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]];
|
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]];
|
||||||
});
|
});
|
||||||
|
|
@ -320,34 +320,34 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
|
|
||||||
- (void)startMonitoringNetworkReachability {
|
- (void)startMonitoringNetworkReachability {
|
||||||
[self stopMonitoringNetworkReachability];
|
[self stopMonitoringNetworkReachability];
|
||||||
|
|
||||||
if (!self.baseURL) {
|
if (!self.baseURL) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
|
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
|
||||||
|
|
||||||
if (!self.networkReachability) {
|
if (!self.networkReachability) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
__weak __typeof(&*self)weakSelf = self;
|
__weak __typeof(&*self)weakSelf = self;
|
||||||
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
|
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
|
||||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||||
if (!strongSelf) {
|
if (!strongSelf) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
strongSelf.networkReachabilityStatus = status;
|
strongSelf.networkReachabilityStatus = status;
|
||||||
if (strongSelf.networkReachabilityStatusBlock) {
|
if (strongSelf.networkReachabilityStatusBlock) {
|
||||||
strongSelf.networkReachabilityStatusBlock(status);
|
strongSelf.networkReachabilityStatusBlock(status);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
||||||
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
|
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
|
||||||
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
|
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.
|
/* 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)) {
|
if (AFURLHostIsIPAddress(self.baseURL)) {
|
||||||
|
|
@ -379,11 +379,11 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
|
if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *className = NSStringFromClass(operationClass);
|
NSString *className = NSStringFromClass(operationClass);
|
||||||
[self.registeredHTTPOperationClassNames removeObject:className];
|
[self.registeredHTTPOperationClassNames removeObject:className];
|
||||||
[self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
|
[self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
|
||||||
|
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -422,16 +422,16 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
parameters:(NSDictionary *)parameters
|
parameters:(NSDictionary *)parameters
|
||||||
{
|
{
|
||||||
NSParameterAssert(method);
|
NSParameterAssert(method);
|
||||||
|
|
||||||
if (!path) {
|
if (!path) {
|
||||||
path = @"";
|
path = @"";
|
||||||
}
|
}
|
||||||
|
|
||||||
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
|
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
|
||||||
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
|
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
|
||||||
[request setHTTPMethod:method];
|
[request setHTTPMethod:method];
|
||||||
[request setAllHTTPHeaderFields:self.defaultHeaders];
|
[request setAllHTTPHeaderFields:self.defaultHeaders];
|
||||||
|
|
||||||
if (parameters) {
|
if (parameters) {
|
||||||
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
|
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
|
||||||
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
|
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
|
||||||
|
|
@ -439,7 +439,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
} else {
|
} else {
|
||||||
NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
|
NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
|
||||||
NSError *error = nil;
|
NSError *error = nil;
|
||||||
|
|
||||||
switch (self.parameterEncoding) {
|
switch (self.parameterEncoding) {
|
||||||
case AFFormURLParameterEncoding:;
|
case AFFormURLParameterEncoding:;
|
||||||
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
|
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
|
||||||
|
|
@ -454,13 +454,13 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
[request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]];
|
[request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
|
NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return request;
|
return request;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -471,11 +471,11 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
{
|
{
|
||||||
NSParameterAssert(method);
|
NSParameterAssert(method);
|
||||||
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
|
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
|
||||||
|
|
||||||
NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
|
NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
|
||||||
|
|
||||||
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
|
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
|
||||||
|
|
||||||
if (parameters) {
|
if (parameters) {
|
||||||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||||
NSData *data = nil;
|
NSData *data = nil;
|
||||||
|
|
@ -486,17 +486,17 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
} else {
|
} else {
|
||||||
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
|
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data) {
|
if (data) {
|
||||||
[formData appendPartWithFormData:data name:[pair.field description]];
|
[formData appendPartWithFormData:data name:[pair.field description]];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (block) {
|
if (block) {
|
||||||
block(formData);
|
block(formData);
|
||||||
}
|
}
|
||||||
|
|
||||||
return [formData requestByFinalizingMultipartFormData];
|
return [formData requestByFinalizingMultipartFormData];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -513,15 +513,15 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
operation = [(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest];
|
operation = [(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!operation) {
|
if (!operation) {
|
||||||
operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
||||||
}
|
}
|
||||||
|
|
||||||
[operation setCompletionBlockWithSuccess:success failure:failure];
|
[operation setCompletionBlockWithSuccess:success failure:failure];
|
||||||
|
|
||||||
operation.credential = self.defaultCredential;
|
operation.credential = self.defaultCredential;
|
||||||
|
|
||||||
return operation;
|
return operation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -535,15 +535,15 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
path:(NSString *)path
|
path:(NSString *)path
|
||||||
{
|
{
|
||||||
NSString *URLStringToMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] absoluteString];
|
NSString *URLStringToMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] absoluteString];
|
||||||
|
|
||||||
for (NSOperation *operation in [self.operationQueue operations]) {
|
for (NSOperation *operation in [self.operationQueue operations]) {
|
||||||
if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
|
if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]];
|
BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]];
|
||||||
BOOL hasMatchingURL = [[[[(AFHTTPRequestOperation *)operation request] URL] absoluteString] isEqualToString:URLStringToMatched];
|
BOOL hasMatchingURL = [[[[(AFHTTPRequestOperation *)operation request] URL] absoluteString] isEqualToString:URLStringToMatched];
|
||||||
|
|
||||||
if (hasMatchingMethod && hasMatchingURL) {
|
if (hasMatchingMethod && hasMatchingURL) {
|
||||||
[operation cancel];
|
[operation cancel];
|
||||||
}
|
}
|
||||||
|
|
@ -559,7 +559,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
|
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
|
||||||
[mutableOperations addObject:operation];
|
[mutableOperations addObject:operation];
|
||||||
}
|
}
|
||||||
|
|
||||||
[self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
|
[self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -578,7 +578,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
dispatch_release(dispatchGroup);
|
dispatch_release(dispatchGroup);
|
||||||
#endif
|
#endif
|
||||||
}];
|
}];
|
||||||
|
|
||||||
for (AFHTTPRequestOperation *operation in operations) {
|
for (AFHTTPRequestOperation *operation in operations) {
|
||||||
AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
|
AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
|
||||||
__weak AFHTTPRequestOperation *weakOperation = operation;
|
__weak AFHTTPRequestOperation *weakOperation = operation;
|
||||||
|
|
@ -588,22 +588,22 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
if (originalCompletionBlock) {
|
if (originalCompletionBlock) {
|
||||||
originalCompletionBlock();
|
originalCompletionBlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
__block NSUInteger numberOfFinishedOperations = 0;
|
__block NSUInteger numberOfFinishedOperations = 0;
|
||||||
[operations enumerateObjectsUsingBlock:^(id obj, __unused NSUInteger idx, __unused BOOL *stop) {
|
[operations enumerateObjectsUsingBlock:^(id obj, __unused NSUInteger idx, __unused BOOL *stop) {
|
||||||
if ([(NSOperation *)obj isFinished]) {
|
if ([(NSOperation *)obj isFinished]) {
|
||||||
numberOfFinishedOperations++;
|
numberOfFinishedOperations++;
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
if (progressBlock) {
|
if (progressBlock) {
|
||||||
progressBlock(numberOfFinishedOperations, [operations count]);
|
progressBlock(numberOfFinishedOperations, [operations count]);
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch_group_leave(dispatchGroup);
|
dispatch_group_leave(dispatchGroup);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
dispatch_group_enter(dispatchGroup);
|
dispatch_group_enter(dispatchGroup);
|
||||||
[batchedOperation addDependency:operation];
|
[batchedOperation addDependency:operation];
|
||||||
}
|
}
|
||||||
|
|
@ -667,17 +667,17 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
|
|
||||||
- (id)initWithCoder:(NSCoder *)aDecoder {
|
- (id)initWithCoder:(NSCoder *)aDecoder {
|
||||||
NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
|
NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
|
||||||
|
|
||||||
self = [self initWithBaseURL:baseURL];
|
self = [self initWithBaseURL:baseURL];
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"];
|
self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"];
|
||||||
self.parameterEncoding = [aDecoder decodeIntegerForKey:@"parameterEncoding"];
|
self.parameterEncoding = [aDecoder decodeIntegerForKey:@"parameterEncoding"];
|
||||||
self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"];
|
self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"];
|
||||||
self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"];
|
self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -693,7 +693,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
||||||
|
|
||||||
- (id)copyWithZone:(NSZone *)zone {
|
- (id)copyWithZone:(NSZone *)zone {
|
||||||
AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
|
AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
|
||||||
|
|
||||||
HTTPClient.stringEncoding = self.stringEncoding;
|
HTTPClient.stringEncoding = self.stringEncoding;
|
||||||
HTTPClient.parameterEncoding = self.parameterEncoding;
|
HTTPClient.parameterEncoding = self.parameterEncoding;
|
||||||
HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames copyWithZone:zone];
|
HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames copyWithZone:zone];
|
||||||
|
|
@ -786,11 +786,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.request = urlRequest;
|
self.request = urlRequest;
|
||||||
self.stringEncoding = encoding;
|
self.stringEncoding = encoding;
|
||||||
self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
|
self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -800,27 +800,27 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
{
|
{
|
||||||
NSParameterAssert(fileURL);
|
NSParameterAssert(fileURL);
|
||||||
NSParameterAssert(name);
|
NSParameterAssert(name);
|
||||||
|
|
||||||
if (![fileURL isFileURL]) {
|
if (![fileURL isFileURL]) {
|
||||||
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
||||||
if (error != NULL) {
|
if (error != NULL) {
|
||||||
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||||
}
|
}
|
||||||
|
|
||||||
return NO;
|
return NO;
|
||||||
} else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
|
} else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
|
||||||
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
||||||
if (error != NULL) {
|
if (error != NULL) {
|
||||||
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||||
}
|
}
|
||||||
|
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, [fileURL lastPathComponent]] forKey:@"Content-Disposition"];
|
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, [fileURL lastPathComponent]] forKey:@"Content-Disposition"];
|
||||||
[mutableHeaders setValue:AFContentTypeForPathExtension([fileURL pathExtension]) forKey:@"Content-Type"];
|
[mutableHeaders setValue:AFContentTypeForPathExtension([fileURL pathExtension]) forKey:@"Content-Type"];
|
||||||
|
|
||||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||||
bodyPart.stringEncoding = self.stringEncoding;
|
bodyPart.stringEncoding = self.stringEncoding;
|
||||||
bodyPart.headers = mutableHeaders;
|
bodyPart.headers = mutableHeaders;
|
||||||
|
|
@ -828,9 +828,9 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
|
|
||||||
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
|
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
|
||||||
bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
|
bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
|
||||||
|
|
||||||
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
||||||
|
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -842,11 +842,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
NSParameterAssert(name);
|
NSParameterAssert(name);
|
||||||
NSParameterAssert(fileName);
|
NSParameterAssert(fileName);
|
||||||
NSParameterAssert(mimeType);
|
NSParameterAssert(mimeType);
|
||||||
|
|
||||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
||||||
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
||||||
|
|
||||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -854,10 +854,10 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
name:(NSString *)name
|
name:(NSString *)name
|
||||||
{
|
{
|
||||||
NSParameterAssert(name);
|
NSParameterAssert(name);
|
||||||
|
|
||||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
|
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
|
||||||
|
|
||||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -865,13 +865,13 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
body:(NSData *)body
|
body:(NSData *)body
|
||||||
{
|
{
|
||||||
NSParameterAssert(body);
|
NSParameterAssert(body);
|
||||||
|
|
||||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||||
bodyPart.stringEncoding = self.stringEncoding;
|
bodyPart.stringEncoding = self.stringEncoding;
|
||||||
bodyPart.headers = headers;
|
bodyPart.headers = headers;
|
||||||
bodyPart.bodyContentLength = [body length];
|
bodyPart.bodyContentLength = [body length];
|
||||||
bodyPart.body = body;
|
bodyPart.body = body;
|
||||||
|
|
||||||
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -886,14 +886,14 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
if ([self.bodyStream isEmpty]) {
|
if ([self.bodyStream isEmpty]) {
|
||||||
return self.request;
|
return self.request;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset the initial and final boundaries to ensure correct Content-Length
|
// Reset the initial and final boundaries to ensure correct Content-Length
|
||||||
[self.bodyStream setInitialAndFinalBoundaries];
|
[self.bodyStream setInitialAndFinalBoundaries];
|
||||||
|
|
||||||
[self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
|
[self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"];
|
||||||
[self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
|
[self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"];
|
||||||
[self.request setHTTPBodyStream:self.bodyStream];
|
[self.request setHTTPBodyStream:self.bodyStream];
|
||||||
|
|
||||||
return self.request;
|
return self.request;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -926,11 +926,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.stringEncoding = encoding;
|
self.stringEncoding = encoding;
|
||||||
self.HTTPBodyParts = [NSMutableArray array];
|
self.HTTPBodyParts = [NSMutableArray array];
|
||||||
self.numberOfBytesInPacket = NSIntegerMax;
|
self.numberOfBytesInPacket = NSIntegerMax;
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -940,7 +940,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
bodyPart.hasInitialBoundary = NO;
|
bodyPart.hasInitialBoundary = NO;
|
||||||
bodyPart.hasFinalBoundary = NO;
|
bodyPart.hasFinalBoundary = NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
[[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES];
|
[[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES];
|
||||||
[[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
|
[[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
|
||||||
}
|
}
|
||||||
|
|
@ -963,7 +963,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
NSInteger bytesRead = 0;
|
NSInteger bytesRead = 0;
|
||||||
|
|
||||||
while ((NSUInteger)bytesRead < MIN(length, self.numberOfBytesInPacket)) {
|
while ((NSUInteger)bytesRead < MIN(length, self.numberOfBytesInPacket)) {
|
||||||
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
|
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
|
||||||
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
|
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
|
||||||
|
|
@ -995,9 +995,9 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
if (self.streamStatus == NSStreamStatusOpen) {
|
if (self.streamStatus == NSStreamStatusOpen) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.streamStatus = NSStreamStatusOpen;
|
self.streamStatus = NSStreamStatusOpen;
|
||||||
|
|
||||||
[self setInitialAndFinalBoundaries];
|
[self setInitialAndFinalBoundaries];
|
||||||
self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
|
self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
|
||||||
}
|
}
|
||||||
|
|
@ -1029,7 +1029,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
||||||
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||||
length += [bodyPart contentLength];
|
length += [bodyPart contentLength];
|
||||||
}
|
}
|
||||||
|
|
||||||
return length;
|
return length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1099,9 +1099,9 @@ typedef enum {
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self transitionToNextPhase];
|
[self transitionToNextPhase];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1130,24 +1130,24 @@ typedef enum {
|
||||||
[headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
|
[headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
|
||||||
}
|
}
|
||||||
[headerString appendString:kAFMultipartFormCRLF];
|
[headerString appendString:kAFMultipartFormCRLF];
|
||||||
|
|
||||||
return [NSString stringWithString:headerString];
|
return [NSString stringWithString:headerString];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (unsigned long long)contentLength {
|
- (unsigned long long)contentLength {
|
||||||
unsigned long long length = 0;
|
unsigned long long length = 0;
|
||||||
|
|
||||||
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
||||||
length += [encapsulationBoundaryData length];
|
length += [encapsulationBoundaryData length];
|
||||||
|
|
||||||
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
||||||
length += [headersData length];
|
length += [headersData length];
|
||||||
|
|
||||||
length += _bodyContentLength;
|
length += _bodyContentLength;
|
||||||
|
|
||||||
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
||||||
length += [closingBoundaryData length];
|
length += [closingBoundaryData length];
|
||||||
|
|
||||||
return length;
|
return length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1156,7 +1156,7 @@ typedef enum {
|
||||||
if (_phase == AFFinalBoundaryPhase) {
|
if (_phase == AFFinalBoundaryPhase) {
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (self.inputStream.streamStatus) {
|
switch (self.inputStream.streamStatus) {
|
||||||
case NSStreamStatusNotOpen:
|
case NSStreamStatusNotOpen:
|
||||||
case NSStreamStatusOpening:
|
case NSStreamStatusOpening:
|
||||||
|
|
@ -1176,27 +1176,27 @@ typedef enum {
|
||||||
maxLength:(NSUInteger)length
|
maxLength:(NSUInteger)length
|
||||||
{
|
{
|
||||||
NSInteger bytesRead = 0;
|
NSInteger bytesRead = 0;
|
||||||
|
|
||||||
if (_phase == AFEncapsulationBoundaryPhase) {
|
if (_phase == AFEncapsulationBoundaryPhase) {
|
||||||
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
||||||
bytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
bytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_phase == AFHeaderPhase) {
|
if (_phase == AFHeaderPhase) {
|
||||||
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
||||||
bytesRead += [self readData:headersData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
bytesRead += [self readData:headersData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_phase == AFBodyPhase) {
|
if (_phase == AFBodyPhase) {
|
||||||
if ([self.inputStream hasBytesAvailable]) {
|
if ([self.inputStream hasBytesAvailable]) {
|
||||||
bytesRead += [self.inputStream read:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
bytesRead += [self.inputStream read:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (![self.inputStream hasBytesAvailable]) {
|
if (![self.inputStream hasBytesAvailable]) {
|
||||||
[self transitionToNextPhase];
|
[self transitionToNextPhase];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_phase == AFFinalBoundaryPhase) {
|
if (_phase == AFFinalBoundaryPhase) {
|
||||||
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
||||||
bytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
bytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||||
|
|
@ -1211,13 +1211,13 @@ typedef enum {
|
||||||
{
|
{
|
||||||
NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
|
NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
|
||||||
[data getBytes:buffer range:range];
|
[data getBytes:buffer range:range];
|
||||||
|
|
||||||
_phaseReadOffset += range.length;
|
_phaseReadOffset += range.length;
|
||||||
|
|
||||||
if (((NSUInteger)_phaseReadOffset) >= [data length]) {
|
if (((NSUInteger)_phaseReadOffset) >= [data length]) {
|
||||||
[self transitionToNextPhase];
|
[self transitionToNextPhase];
|
||||||
}
|
}
|
||||||
|
|
||||||
return (NSInteger)range.length;
|
return (NSInteger)range.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1226,7 +1226,7 @@ typedef enum {
|
||||||
[self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES];
|
[self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES];
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (_phase) {
|
switch (_phase) {
|
||||||
case AFEncapsulationBoundaryPhase:
|
case AFEncapsulationBoundaryPhase:
|
||||||
_phase = AFHeaderPhase;
|
_phase = AFHeaderPhase;
|
||||||
|
|
@ -1246,7 +1246,7 @@ typedef enum {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
_phaseReadOffset = 0;
|
_phaseReadOffset = 0;
|
||||||
|
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFHTTPRequestOperation.h
|
// AFHTTPRequestOperation.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -51,12 +51,12 @@
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, readonly) BOOL hasAcceptableContentType;
|
@property (nonatomic, readonly) BOOL hasAcceptableContentType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
|
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
|
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
|
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
|
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
|
||||||
|
|
@ -67,21 +67,21 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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
|
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.
|
By default, this is the range 200 to 299, inclusive.
|
||||||
*/
|
*/
|
||||||
+ (NSIndexSet *)acceptableStatusCodes;
|
+ (NSIndexSet *)acceptableStatusCodes;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
|
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
|
||||||
|
|
||||||
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
|
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
|
||||||
*/
|
*/
|
||||||
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
|
+ (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
|
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`.
|
By default, this is `nil`.
|
||||||
*/
|
*/
|
||||||
+ (NSSet *)acceptableContentTypes;
|
+ (NSSet *)acceptableContentTypes;
|
||||||
|
|
@ -100,7 +100,7 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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`.
|
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.
|
@param urlRequest The request that is determined to be supported or not supported for this class.
|
||||||
*/
|
*/
|
||||||
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
|
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
|
||||||
|
|
@ -111,10 +111,10 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
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.
|
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 success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
|
||||||
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
|
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
|
||||||
|
|
||||||
@discussion This method should be overridden in subclasses in order to specify the response object passed into the success block.
|
@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
|
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFHTTPRequestOperation.m
|
// AFHTTPRequestOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -25,12 +25,12 @@
|
||||||
|
|
||||||
// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
|
// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
|
||||||
#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
|
#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
|
||||||
#define AF_CAST_TO_BLOCK id
|
#define AF_CAST_TO_BLOCK id
|
||||||
#else
|
#else
|
||||||
#define AF_CAST_TO_BLOCK __bridge void *
|
#define AF_CAST_TO_BLOCK __bridge void *
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// We do a little bit of duck typing in this file which can trigger this warning. Turn it off for this source file.
|
// We do a little bit of duck typing in this file which can trigger this warning. Turn it off for this source file.
|
||||||
#pragma clang diagnostic push
|
#pragma clang diagnostic push
|
||||||
#pragma clang diagnostic ignored "-Wstrict-selector-match"
|
#pragma clang diagnostic ignored "-Wstrict-selector-match"
|
||||||
|
|
||||||
|
|
@ -47,9 +47,9 @@ NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
|
||||||
if (parametersRange.location != NSNotFound) {
|
if (parametersRange.location != NSNotFound) {
|
||||||
mediaRange = [mediaRange substringToIndex:parametersRange.location];
|
mediaRange = [mediaRange substringToIndex:parametersRange.location];
|
||||||
}
|
}
|
||||||
|
|
||||||
mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
||||||
|
|
||||||
if (mediaRange.length > 0) {
|
if (mediaRange.length > 0) {
|
||||||
[mutableContentTypes addObject:mediaRange];
|
[mutableContentTypes addObject:mediaRange];
|
||||||
}
|
}
|
||||||
|
|
@ -130,7 +130,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
#endif
|
#endif
|
||||||
_successCallbackQueue = NULL;
|
_successCallbackQueue = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_failureCallbackQueue) {
|
if (_failureCallbackQueue) {
|
||||||
#if !OS_OBJECT_USE_OBJC
|
#if !OS_OBJECT_USE_OBJC
|
||||||
dispatch_release(_failureCallbackQueue);
|
dispatch_release(_failureCallbackQueue);
|
||||||
|
|
@ -147,7 +147,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
|
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
|
||||||
[userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
|
[userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
|
||||||
[userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
|
[userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
|
||||||
|
|
||||||
if (![self hasAcceptableStatusCode]) {
|
if (![self hasAcceptableStatusCode]) {
|
||||||
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
||||||
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
|
[userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey];
|
||||||
|
|
@ -161,7 +161,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self.HTTPError) {
|
if (self.HTTPError) {
|
||||||
return self.HTTPError;
|
return self.HTTPError;
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -189,7 +189,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)pause {
|
- (void)pause {
|
||||||
unsigned long long offset = 0;
|
unsigned long long offset = 0;
|
||||||
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
|
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
|
||||||
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
|
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -202,7 +202,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
}
|
}
|
||||||
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
|
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
|
||||||
self.request = mutableURLRequest;
|
self.request = mutableURLRequest;
|
||||||
|
|
||||||
[super pause];
|
[super pause];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -210,7 +210,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
if (!self.response) {
|
if (!self.response) {
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
||||||
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
|
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
|
||||||
}
|
}
|
||||||
|
|
@ -219,14 +219,14 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
if (!self.response) {
|
if (!self.response) {
|
||||||
return NO;
|
return NO;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
|
// Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".
|
||||||
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
|
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
|
||||||
NSString *contentType = [self.response MIMEType];
|
NSString *contentType = [self.response MIMEType];
|
||||||
if (!contentType) {
|
if (!contentType) {
|
||||||
contentType = @"application/octet-stream";
|
contentType = @"application/octet-stream";
|
||||||
}
|
}
|
||||||
|
|
||||||
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
|
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -245,7 +245,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
#endif
|
#endif
|
||||||
_successCallbackQueue = successCallbackQueue;
|
_successCallbackQueue = successCallbackQueue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
|
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
|
||||||
|
|
@ -256,14 +256,14 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
#endif
|
#endif
|
||||||
_failureCallbackQueue = NULL;
|
_failureCallbackQueue = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (failureCallbackQueue) {
|
if (failureCallbackQueue) {
|
||||||
#if !OS_OBJECT_USE_OBJC
|
#if !OS_OBJECT_USE_OBJC
|
||||||
dispatch_retain(failureCallbackQueue);
|
dispatch_retain(failureCallbackQueue);
|
||||||
#endif
|
#endif
|
||||||
_failureCallbackQueue = failureCallbackQueue;
|
_failureCallbackQueue = failureCallbackQueue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
|
|
@ -320,17 +320,17 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
||||||
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
|
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
|
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
|
||||||
}
|
}
|
||||||
|
|
||||||
#pragma mark - NSURLConnectionDelegate
|
#pragma mark - NSURLConnectionDelegate
|
||||||
|
|
||||||
- (void)connection:(__unused NSURLConnection *)connection
|
- (void)connection:(__unused NSURLConnection *)connection
|
||||||
didReceiveResponse:(NSURLResponse *)response
|
didReceiveResponse:(NSURLResponse *)response
|
||||||
{
|
{
|
||||||
self.response = (NSHTTPURLResponse *)response;
|
self.response = (NSHTTPURLResponse *)response;
|
||||||
|
|
||||||
// Set Content-Range header if status code of response is 206 (Partial Content)
|
// Set Content-Range header if status code of response is 206 (Partial Content)
|
||||||
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
|
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
|
||||||
long long totalContentLength = self.response.expectedContentLength;
|
long long totalContentLength = self.response.expectedContentLength;
|
||||||
|
|
@ -351,7 +351,7 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
} else {
|
} else {
|
||||||
if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) {
|
if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) {
|
||||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||||
|
|
||||||
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
||||||
for (NSString *runLoopMode in self.runLoopModes) {
|
for (NSString *runLoopMode in self.runLoopModes) {
|
||||||
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||||
|
|
@ -359,7 +359,7 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.offsetContentLength = MAX(fileOffset, 0);
|
self.offsetContentLength = MAX(fileOffset, 0);
|
||||||
self.totalContentLength = totalContentLength;
|
self.totalContentLength = totalContentLength;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFImageRequestOperation.h
|
// AFImageRequestOperation.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -26,18 +26,18 @@
|
||||||
#import <Availability.h>
|
#import <Availability.h>
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
#import <UIKit/UIKit.h>
|
#import <UIKit/UIKit.h>
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
#import <Cocoa/Cocoa.h>
|
#import <Cocoa/Cocoa.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
|
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
|
||||||
|
|
||||||
## Acceptable Content Types
|
## Acceptable Content Types
|
||||||
|
|
||||||
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||||
|
|
||||||
- `image/tiff`
|
- `image/tiff`
|
||||||
- `image/jpeg`
|
- `image/jpeg`
|
||||||
- `image/gif`
|
- `image/gif`
|
||||||
|
|
@ -69,28 +69,28 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
|
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 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.
|
@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
|
@return A new image request operation
|
||||||
*/
|
*/
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
success:(void (^)(UIImage *image))success;
|
success:(void (^)(UIImage *image))success;
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
success:(void (^)(NSImage *image))success;
|
success:(void (^)(NSImage *image))success;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
|
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 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 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 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.
|
@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
|
@return A new image request operation
|
||||||
*/
|
*/
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFImageRequestOperation.m
|
// AFImageRequestOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
if (af_image_request_operation_processing_queue == NULL) {
|
if (af_image_request_operation_processing_queue == NULL) {
|
||||||
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
|
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return af_image_request_operation_processing_queue;
|
return af_image_request_operation_processing_queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,7 +46,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
success:(void (^)(UIImage *image))success
|
success:(void (^)(UIImage *image))success
|
||||||
{
|
{
|
||||||
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
|
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
|
||||||
|
|
@ -56,7 +56,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
} failure:nil];
|
} failure:nil];
|
||||||
}
|
}
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
success:(void (^)(NSImage *image))success
|
success:(void (^)(NSImage *image))success
|
||||||
{
|
{
|
||||||
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
|
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
|
||||||
|
|
@ -95,8 +95,8 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error);
|
failure(operation.request, operation.response, error);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
|
|
@ -126,7 +126,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error);
|
failure(operation.request, operation.response, error);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
@ -136,11 +136,11 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
self.imageScale = [[UIScreen mainScreen] scale];
|
self.imageScale = [[UIScreen mainScreen] scale];
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -149,10 +149,10 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
- (UIImage *)responseImage {
|
- (UIImage *)responseImage {
|
||||||
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
|
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
|
||||||
UIImage *image = [UIImage imageWithData:self.responseData];
|
UIImage *image = [UIImage imageWithData:self.responseData];
|
||||||
|
|
||||||
self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
|
self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responseImage;
|
return _responseImage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -163,9 +163,9 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
#pragma clang diagnostic pop
|
#pragma clang diagnostic pop
|
||||||
|
|
||||||
_imageScale = imageScale;
|
_imageScale = imageScale;
|
||||||
|
|
||||||
self.responseImage = nil;
|
self.responseImage = nil;
|
||||||
}
|
}
|
||||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||||
|
|
@ -176,7 +176,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
|
self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
|
||||||
[self.responseImage addRepresentation:bitimage];
|
[self.responseImage addRepresentation:bitimage];
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responseImage;
|
return _responseImage;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
@ -193,8 +193,8 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
dispatch_once(&onceToken, ^{
|
dispatch_once(&onceToken, ^{
|
||||||
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
|
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
|
||||||
});
|
});
|
||||||
|
|
||||||
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
|
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||||
|
|
@ -210,7 +210,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
||||||
failure(self, self.error);
|
failure(self, self.error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (success) {
|
if (success) {
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
UIImage *image = nil;
|
UIImage *image = nil;
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,7 @@
|
||||||
@return A new JSON request operation
|
@return A new JSON request operation
|
||||||
*/
|
*/
|
||||||
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
|
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
|
||||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
|
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
|
||||||
|
|
||||||
@end
|
@end
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFJSONRequestOperation.m
|
// AFJSONRequestOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
if (af_json_request_operation_processing_queue == NULL) {
|
if (af_json_request_operation_processing_queue == NULL) {
|
||||||
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0);
|
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return af_json_request_operation_processing_queue;
|
return af_json_request_operation_processing_queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -55,7 +55,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
|
failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -74,10 +74,10 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
NSData *JSONData = [self.responseString dataUsingEncoding:self.responseStringEncoding];
|
NSData *JSONData = [self.responseString dataUsingEncoding:self.responseStringEncoding];
|
||||||
self.responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:self.JSONReadingOptions error:&error];
|
self.responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:self.JSONReadingOptions error:&error];
|
||||||
}
|
}
|
||||||
|
|
||||||
self.JSONError = error;
|
self.JSONError = error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responseJSON;
|
return _responseJSON;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -104,7 +104,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
{
|
{
|
||||||
#pragma clang diagnostic push
|
#pragma clang diagnostic push
|
||||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||||
self.completionBlock = ^ {
|
self.completionBlock = ^ {
|
||||||
if (self.error) {
|
if (self.error) {
|
||||||
if (failure) {
|
if (failure) {
|
||||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
|
|
@ -114,7 +114,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
} else {
|
} else {
|
||||||
dispatch_async(json_request_operation_processing_queue(), ^{
|
dispatch_async(json_request_operation_processing_queue(), ^{
|
||||||
id JSON = self.responseJSON;
|
id JSON = self.responseJSON;
|
||||||
|
|
||||||
if (self.JSONError) {
|
if (self.JSONError) {
|
||||||
if (failure) {
|
if (failure) {
|
||||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
|
|
@ -126,7 +126,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
||||||
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
success(self, JSON);
|
success(self, JSON);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFNetworkActivityIndicatorManager.h
|
// AFNetworkActivityIndicatorManager.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -29,21 +29,21 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
|
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
|
||||||
|
|
||||||
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
|
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
|
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
|
||||||
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
|
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
|
||||||
*/
|
*/
|
||||||
@interface AFNetworkActivityIndicatorManager : NSObject
|
@interface AFNetworkActivityIndicatorManager : NSObject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
A Boolean value indicating whether the manager is enabled.
|
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.
|
@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;
|
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
|
||||||
|
|
@ -51,11 +51,11 @@
|
||||||
/**
|
/**
|
||||||
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
|
A Boolean value indicating whether the network activity indicator is currently displayed in the status bar.
|
||||||
*/
|
*/
|
||||||
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Returns the shared network activity indicator manager object for the system.
|
Returns the shared network activity indicator manager object for the system.
|
||||||
|
|
||||||
@return The systemwide network activity indicator manager.
|
@return The systemwide network activity indicator manager.
|
||||||
*/
|
*/
|
||||||
+ (instancetype)sharedManager;
|
+ (instancetype)sharedManager;
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFNetworkActivityIndicatorManager.m
|
// AFNetworkActivityIndicatorManager.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -48,7 +48,7 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
|
||||||
dispatch_once(&oncePredicate, ^{
|
dispatch_once(&oncePredicate, ^{
|
||||||
_sharedManager = [[self alloc] init];
|
_sharedManager = [[self alloc] init];
|
||||||
});
|
});
|
||||||
|
|
||||||
return _sharedManager;
|
return _sharedManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -61,18 +61,18 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil];
|
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil];
|
||||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil];
|
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)dealloc {
|
- (void)dealloc {
|
||||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||||
|
|
||||||
[_activityIndicatorVisibilityTimer invalidate];
|
[_activityIndicatorVisibilityTimer invalidate];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
|
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFPropertyListRequestOperation.h
|
// AFPropertyListRequestOperation.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -25,11 +25,11 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
|
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
|
||||||
|
|
||||||
## Acceptable Content Types
|
## Acceptable Content Types
|
||||||
|
|
||||||
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
|
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
|
||||||
|
|
||||||
- `application/x-plist`
|
- `application/x-plist`
|
||||||
*/
|
*/
|
||||||
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
|
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
|
||||||
|
|
@ -54,11 +54,11 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
|
Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
|
||||||
|
|
||||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation
|
@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 object deserialized from a plist constructed using the response data.
|
@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 object deserialized from a plist constructed using the response data.
|
||||||
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. 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 property list request operation
|
@return A new property list request operation
|
||||||
*/
|
*/
|
||||||
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFPropertyListRequestOperation.m
|
// AFPropertyListRequestOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
if (af_property_list_request_operation_processing_queue == NULL) {
|
if (af_property_list_request_operation_processing_queue == NULL) {
|
||||||
af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0);
|
af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return af_property_list_request_operation_processing_queue;
|
return af_property_list_request_operation_processing_queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -57,7 +57,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
|
failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -66,9 +66,9 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.propertyListReadOptions = NSPropertyListImmutable;
|
self.propertyListReadOptions = NSPropertyListImmutable;
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -81,7 +81,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
self.propertyListFormat = format;
|
self.propertyListFormat = format;
|
||||||
self.propertyListError = error;
|
self.propertyListError = error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responsePropertyList;
|
return _responsePropertyList;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -108,7 +108,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
{
|
{
|
||||||
#pragma clang diagnostic push
|
#pragma clang diagnostic push
|
||||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||||
self.completionBlock = ^ {
|
self.completionBlock = ^ {
|
||||||
if (self.error) {
|
if (self.error) {
|
||||||
if (failure) {
|
if (failure) {
|
||||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
|
|
@ -118,7 +118,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
} else {
|
} else {
|
||||||
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
|
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
|
||||||
id propertyList = self.responsePropertyList;
|
id propertyList = self.responsePropertyList;
|
||||||
|
|
||||||
if (self.propertyListError) {
|
if (self.propertyListError) {
|
||||||
if (failure) {
|
if (failure) {
|
||||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
|
|
@ -130,7 +130,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
||||||
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
success(self, propertyList);
|
success(self, propertyList);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFURLConnectionOperation.h
|
// AFURLConnectionOperation.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -26,17 +26,17 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
|
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
|
||||||
|
|
||||||
## Subclassing Notes
|
## Subclassing Notes
|
||||||
|
|
||||||
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
|
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
|
||||||
|
|
||||||
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
|
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes.
|
||||||
|
|
||||||
## NSURLConnection Delegate Methods
|
## NSURLConnection Delegate Methods
|
||||||
|
|
||||||
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
|
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
|
||||||
|
|
||||||
- `connection:didReceiveResponse:`
|
- `connection:didReceiveResponse:`
|
||||||
- `connection:didReceiveData:`
|
- `connection:didReceiveData:`
|
||||||
- `connectionDidFinishLoading:`
|
- `connectionDidFinishLoading:`
|
||||||
|
|
@ -47,30 +47,30 @@
|
||||||
- `connection:didReceiveAuthenticationChallenge:`
|
- `connection:didReceiveAuthenticationChallenge:`
|
||||||
- `connectionShouldUseCredentialStorage:`
|
- `connectionShouldUseCredentialStorage:`
|
||||||
- `connection:needNewBodyStream:`
|
- `connection:needNewBodyStream:`
|
||||||
|
|
||||||
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
|
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
|
||||||
|
|
||||||
## Class Constructors
|
## Class Constructors
|
||||||
|
|
||||||
Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
|
Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
|
||||||
|
|
||||||
## Callbacks and Completion Blocks
|
## Callbacks and Completion Blocks
|
||||||
|
|
||||||
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
|
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
|
||||||
|
|
||||||
Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
|
Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/).
|
||||||
|
|
||||||
## NSCoding & NSCopying Conformance
|
## NSCoding & NSCopying Conformance
|
||||||
|
|
||||||
`AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
|
`AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
|
||||||
|
|
||||||
### NSCoding Caveats
|
### NSCoding Caveats
|
||||||
|
|
||||||
- Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
|
- Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`.
|
||||||
- Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
|
- Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged.
|
||||||
|
|
||||||
### NSCopying Caveats
|
### NSCopying Caveats
|
||||||
|
|
||||||
- `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
|
- `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.
|
||||||
- A copy of an operation will not include the `outputStream` of the original.
|
- A copy of an operation will not include the `outputStream` of the original.
|
||||||
- Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
|
- Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied.
|
||||||
|
|
@ -110,7 +110,7 @@
|
||||||
///----------------------------
|
///----------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The data received during the request.
|
The data received during the request.
|
||||||
*/
|
*/
|
||||||
@property (readonly, nonatomic, strong) NSData *responseData;
|
@property (readonly, nonatomic, strong) NSData *responseData;
|
||||||
|
|
||||||
|
|
@ -121,8 +121,8 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The string encoding of the response.
|
The string encoding of the response.
|
||||||
|
|
||||||
@discussion If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
|
@discussion If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`.
|
||||||
*/
|
*/
|
||||||
@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
|
@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding;
|
||||||
|
|
||||||
|
|
@ -133,14 +133,14 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
|
Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
|
||||||
|
|
||||||
@discussion This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
|
@discussion This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
|
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
|
The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
|
||||||
|
|
||||||
@discussion This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
|
@discussion This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, strong) NSURLCredential *credential;
|
@property (nonatomic, strong) NSURLCredential *credential;
|
||||||
|
|
@ -150,15 +150,15 @@
|
||||||
///------------------------
|
///------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The input stream used to read data to be sent during the request.
|
The input stream used to read data to be sent during the request.
|
||||||
|
|
||||||
@discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`.
|
@discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, strong) NSInputStream *inputStream;
|
@property (nonatomic, strong) NSInputStream *inputStream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
The output stream that is used to write data received until the request is finished.
|
The output stream that is used to write data received until the request is finished.
|
||||||
|
|
||||||
@discussion By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
|
@discussion By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set.
|
||||||
*/
|
*/
|
||||||
@property (nonatomic, strong) NSOutputStream *outputStream;
|
@property (nonatomic, strong) NSOutputStream *outputStream;
|
||||||
|
|
@ -178,9 +178,9 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
|
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
|
||||||
|
|
||||||
@param urlRequest The request object to be used by the operation connection.
|
@param urlRequest The request object to be used by the operation connection.
|
||||||
|
|
||||||
@discussion This is the designated initializer.
|
@discussion This is the designated initializer.
|
||||||
*/
|
*/
|
||||||
- (id)initWithRequest:(NSURLRequest *)urlRequest;
|
- (id)initWithRequest:(NSURLRequest *)urlRequest;
|
||||||
|
|
@ -191,21 +191,21 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Pauses the execution of the request operation.
|
Pauses the execution of the request operation.
|
||||||
|
|
||||||
@discussion A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
|
@discussion A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
|
||||||
*/
|
*/
|
||||||
- (void)pause;
|
- (void)pause;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Whether the request operation is currently paused.
|
Whether the request operation is currently paused.
|
||||||
|
|
||||||
@return `YES` if the operation is currently paused, otherwise `NO`.
|
@return `YES` if the operation is currently paused, otherwise `NO`.
|
||||||
*/
|
*/
|
||||||
- (BOOL)isPaused;
|
- (BOOL)isPaused;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Resumes the execution of the paused request operation.
|
Resumes the execution of the paused request operation.
|
||||||
|
|
||||||
@discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
|
@discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request.
|
||||||
*/
|
*/
|
||||||
- (void)resume;
|
- (void)resume;
|
||||||
|
|
@ -216,8 +216,8 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
|
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
|
||||||
|
|
||||||
@param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
|
@param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
|
||||||
*/
|
*/
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
|
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler;
|
||||||
|
|
@ -229,14 +229,14 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
|
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
|
||||||
|
|
||||||
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
|
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
|
||||||
*/
|
*/
|
||||||
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
|
- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
|
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
|
||||||
|
|
||||||
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
|
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread.
|
||||||
*/
|
*/
|
||||||
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
|
- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block;
|
||||||
|
|
@ -247,25 +247,25 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a block to be executed to determine whether the connection should be able to respond to a protection space's form of authentication, as handled by the `NSURLConnectionDelegate` method `connection:canAuthenticateAgainstProtectionSpace:`.
|
Sets a block to be executed to determine whether the connection should be able to respond to a protection space's form of authentication, as handled by the `NSURLConnectionDelegate` method `connection:canAuthenticateAgainstProtectionSpace:`.
|
||||||
|
|
||||||
@param block A block object to be executed to determine whether the connection should be able to respond to a protection space's form of authentication. The block has a `BOOL` return type and takes two arguments: the URL connection object, and the protection space to authenticate against.
|
@param block A block object to be executed to determine whether the connection should be able to respond to a protection space's form of authentication. The block has a `BOOL` return type and takes two arguments: the URL connection object, and the protection space to authenticate against.
|
||||||
|
|
||||||
@discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:canAuthenticateAgainstProtectionSpace:` will accept invalid SSL certificates, returning `YES` if the protection space authentication method is `NSURLAuthenticationMethodServerTrust`.
|
@discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:canAuthenticateAgainstProtectionSpace:` will accept invalid SSL certificates, returning `YES` if the protection space authentication method is `NSURLAuthenticationMethodServerTrust`.
|
||||||
*/
|
*/
|
||||||
- (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block;
|
- (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:didReceiveAuthenticationChallenge:`.
|
Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:didReceiveAuthenticationChallenge:`.
|
||||||
|
|
||||||
@param block A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated.
|
@param block A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated.
|
||||||
|
|
||||||
@discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:didReceiveAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
|
@discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:didReceiveAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates.
|
||||||
*/
|
*/
|
||||||
- (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
|
- (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
|
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`.
|
||||||
|
|
||||||
@param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
|
@param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect.
|
||||||
*/
|
*/
|
||||||
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
|
- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block;
|
||||||
|
|
@ -273,7 +273,7 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
|
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`.
|
||||||
|
|
||||||
@param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
|
@param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
|
||||||
*/
|
*/
|
||||||
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
|
- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;
|
||||||
|
|
@ -286,28 +286,28 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
## User info dictionary keys
|
## User info dictionary keys
|
||||||
|
|
||||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||||
|
|
||||||
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
||||||
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
||||||
|
|
||||||
### Constants
|
### Constants
|
||||||
|
|
||||||
`AFNetworkingOperationFailingURLRequestErrorKey`
|
`AFNetworkingOperationFailingURLRequestErrorKey`
|
||||||
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
|
The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
|
||||||
|
|
||||||
`AFNetworkingOperationFailingURLResponseErrorKey`
|
`AFNetworkingOperationFailingURLResponseErrorKey`
|
||||||
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
|
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`.
|
||||||
|
|
||||||
## Error Domains
|
## Error Domains
|
||||||
|
|
||||||
The following error domain is predefined.
|
The following error domain is predefined.
|
||||||
|
|
||||||
- `NSString * const AFNetworkingErrorDomain`
|
- `NSString * const AFNetworkingErrorDomain`
|
||||||
|
|
||||||
### Constants
|
### Constants
|
||||||
|
|
||||||
`AFNetworkingErrorDomain`
|
`AFNetworkingErrorDomain`
|
||||||
AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFURLConnectionOperation.m
|
// AFURLConnectionOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -23,7 +23,7 @@
|
||||||
#import "AFURLConnectionOperation.h"
|
#import "AFURLConnectionOperation.h"
|
||||||
|
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
#import <UIKit/UIKit.h>
|
#import <UIKit/UIKit.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if !__has_feature(objc_arc)
|
#if !__has_feature(objc_arc)
|
||||||
|
|
@ -167,19 +167,19 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
+ (NSThread *)networkRequestThread {
|
+ (NSThread *)networkRequestThread {
|
||||||
static NSThread *_networkRequestThread = nil;
|
static NSThread *_networkRequestThread = nil;
|
||||||
static dispatch_once_t oncePredicate;
|
static dispatch_once_t oncePredicate;
|
||||||
|
|
||||||
dispatch_once(&oncePredicate, ^{
|
dispatch_once(&oncePredicate, ^{
|
||||||
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
|
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
|
||||||
[_networkRequestThread start];
|
[_networkRequestThread start];
|
||||||
});
|
});
|
||||||
|
|
||||||
return _networkRequestThread;
|
return _networkRequestThread;
|
||||||
}
|
}
|
||||||
|
|
||||||
+ (NSArray *)pinnedCertificates {
|
+ (NSArray *)pinnedCertificates {
|
||||||
static NSArray *_pinnedCertificates = nil;
|
static NSArray *_pinnedCertificates = nil;
|
||||||
static dispatch_once_t onceToken;
|
static dispatch_once_t onceToken;
|
||||||
|
|
||||||
dispatch_once(&onceToken, ^{
|
dispatch_once(&onceToken, ^{
|
||||||
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
|
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
|
||||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
|
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
|
||||||
|
|
@ -190,7 +190,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
}
|
}
|
||||||
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
|
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
|
||||||
});
|
});
|
||||||
|
|
||||||
return _pinnedCertificates;
|
return _pinnedCertificates;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -199,20 +199,20 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.lock = [[NSRecursiveLock alloc] init];
|
self.lock = [[NSRecursiveLock alloc] init];
|
||||||
self.lock.name = kAFNetworkingLockName;
|
self.lock.name = kAFNetworkingLockName;
|
||||||
|
|
||||||
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
|
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
|
||||||
|
|
||||||
self.request = urlRequest;
|
self.request = urlRequest;
|
||||||
|
|
||||||
self.shouldUseCredentialStorage = YES;
|
self.shouldUseCredentialStorage = YES;
|
||||||
|
|
||||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||||
|
|
||||||
self.state = AFOperationReadyState;
|
self.state = AFOperationReadyState;
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -242,7 +242,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
__weak __typeof(&*self)weakSelf = self;
|
__weak __typeof(&*self)weakSelf = self;
|
||||||
[super setCompletionBlock:^ {
|
[super setCompletionBlock:^ {
|
||||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||||
|
|
||||||
block();
|
block();
|
||||||
[strongSelf setCompletionBlock:nil];
|
[strongSelf setCompletionBlock:nil];
|
||||||
}];
|
}];
|
||||||
|
|
@ -266,7 +266,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
if (outputStream == _outputStream) {
|
if (outputStream == _outputStream) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self willChangeValueForKey:@"outputStream"];
|
[self willChangeValueForKey:@"outputStream"];
|
||||||
if (_outputStream) {
|
if (_outputStream) {
|
||||||
[_outputStream close];
|
[_outputStream close];
|
||||||
|
|
@ -278,19 +278,19 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||||
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
|
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
|
||||||
[self.lock lock];
|
[self.lock lock];
|
||||||
if (!self.backgroundTaskIdentifier) {
|
if (!self.backgroundTaskIdentifier) {
|
||||||
UIApplication *application = [UIApplication sharedApplication];
|
UIApplication *application = [UIApplication sharedApplication];
|
||||||
__weak __typeof(&*self)weakSelf = self;
|
__weak __typeof(&*self)weakSelf = self;
|
||||||
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
|
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
|
||||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||||
|
|
||||||
if (handler) {
|
if (handler) {
|
||||||
handler();
|
handler();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (strongSelf) {
|
if (strongSelf) {
|
||||||
[strongSelf cancel];
|
[strongSelf cancel];
|
||||||
|
|
||||||
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
|
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
|
||||||
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
|
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
|
||||||
}
|
}
|
||||||
|
|
@ -329,13 +329,13 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
if (AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
|
if (AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
|
||||||
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
|
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
|
||||||
NSString *newStateKey = AFKeyPathFromOperationState(state);
|
NSString *newStateKey = AFKeyPathFromOperationState(state);
|
||||||
|
|
||||||
[self willChangeValueForKey:newStateKey];
|
[self willChangeValueForKey:newStateKey];
|
||||||
[self willChangeValueForKey:oldStateKey];
|
[self willChangeValueForKey:oldStateKey];
|
||||||
_state = state;
|
_state = state;
|
||||||
[self didChangeValueForKey:oldStateKey];
|
[self didChangeValueForKey:oldStateKey];
|
||||||
[self didChangeValueForKey:newStateKey];
|
[self didChangeValueForKey:newStateKey];
|
||||||
|
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
switch (state) {
|
switch (state) {
|
||||||
case AFOperationExecutingState:
|
case AFOperationExecutingState:
|
||||||
|
|
@ -358,7 +358,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
|
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
|
||||||
}
|
}
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
|
|
||||||
return _responseString;
|
return _responseString;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -372,11 +372,11 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
|
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.responseStringEncoding = stringEncoding;
|
self.responseStringEncoding = stringEncoding;
|
||||||
}
|
}
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
|
|
||||||
return _responseStringEncoding;
|
return _responseStringEncoding;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -384,17 +384,17 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
|
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self.lock lock];
|
[self.lock lock];
|
||||||
|
|
||||||
if ([self isExecuting]) {
|
if ([self isExecuting]) {
|
||||||
[self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
[self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
||||||
|
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
|
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
self.state = AFOperationPausedState;
|
self.state = AFOperationPausedState;
|
||||||
|
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
|
|
@ -408,10 +408,10 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
if (![self isPaused]) {
|
if (![self isPaused]) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self.lock lock];
|
[self.lock lock];
|
||||||
self.state = AFOperationReadyState;
|
self.state = AFOperationReadyState;
|
||||||
|
|
||||||
[self start];
|
[self start];
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
}
|
}
|
||||||
|
|
@ -438,7 +438,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
[self.lock lock];
|
[self.lock lock];
|
||||||
if ([self isReady]) {
|
if ([self isReady]) {
|
||||||
self.state = AFOperationExecutingState;
|
self.state = AFOperationExecutingState;
|
||||||
|
|
||||||
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
||||||
}
|
}
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
|
|
@ -450,14 +450,14 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
[self finish];
|
[self finish];
|
||||||
} else {
|
} else {
|
||||||
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
|
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
|
||||||
|
|
||||||
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
||||||
for (NSString *runLoopMode in self.runLoopModes) {
|
for (NSString *runLoopMode in self.runLoopModes) {
|
||||||
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
|
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||||
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||||
}
|
}
|
||||||
|
|
||||||
[self.connection start];
|
[self.connection start];
|
||||||
}
|
}
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
}
|
}
|
||||||
|
|
@ -474,7 +474,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
[super cancel];
|
[super cancel];
|
||||||
[self didChangeValueForKey:@"isCancelled"];
|
[self didChangeValueForKey:@"isCancelled"];
|
||||||
|
|
||||||
// Cancel the connection on the thread it runs on to prevent race conditions
|
// Cancel the connection on the thread it runs on to prevent race conditions
|
||||||
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
[self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
||||||
}
|
}
|
||||||
[self.lock unlock];
|
[self.lock unlock];
|
||||||
|
|
@ -489,7 +489,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
||||||
|
|
||||||
if (self.connection) {
|
if (self.connection) {
|
||||||
[self.connection cancel];
|
[self.connection cancel];
|
||||||
|
|
||||||
// Manually send this delegate message since `[self.connection cancel]` causes the connection to never send another message to its delegate
|
// Manually send this delegate message since `[self.connection cancel]` causes the connection to never send another message to its delegate
|
||||||
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.error];
|
[self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.error];
|
||||||
}
|
}
|
||||||
|
|
@ -505,7 +505,7 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
|
||||||
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
|
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
|
||||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
|
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
|
||||||
NSData *certificateData = (__bridge_transfer NSData *)SecCertificateCopyData(certificate);
|
NSData *certificateData = (__bridge_transfer NSData *)SecCertificateCopyData(certificate);
|
||||||
|
|
||||||
if ([[[self class] pinnedCertificates] containsObject:certificateData]) {
|
if ([[[self class] pinnedCertificates] containsObject:certificateData]) {
|
||||||
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
|
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
|
||||||
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
||||||
|
|
@ -516,7 +516,7 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
- (BOOL)connection:(NSURLConnection *)connection
|
- (BOOL)connection:(NSURLConnection *)connection
|
||||||
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
||||||
{
|
{
|
||||||
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
||||||
|
|
@ -524,7 +524,7 @@ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (self.authenticationAgainstProtectionSpace) {
|
if (self.authenticationAgainstProtectionSpace) {
|
||||||
return self.authenticationAgainstProtectionSpace(connection, protectionSpace);
|
return self.authenticationAgainstProtectionSpace(connection, protectionSpace);
|
||||||
} else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
|
} else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
|
||||||
|
|
@ -534,8 +534,8 @@ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)connection:(NSURLConnection *)connection
|
- (void)connection:(NSURLConnection *)connection
|
||||||
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||||
{
|
{
|
||||||
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
||||||
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
|
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
|
||||||
|
|
@ -543,7 +543,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (self.authenticationChallenge) {
|
if (self.authenticationChallenge) {
|
||||||
self.authenticationChallenge(connection, challenge);
|
self.authenticationChallenge(connection, challenge);
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -564,7 +564,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||||
if (!credential) {
|
if (!credential) {
|
||||||
credential = self.credential;
|
credential = self.credential;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (credential) {
|
if (credential) {
|
||||||
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -603,7 +603,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||||
|
|
||||||
- (void)connection:(NSURLConnection __unused *)connection
|
- (void)connection:(NSURLConnection __unused *)connection
|
||||||
didSendBodyData:(NSInteger)bytesWritten
|
didSendBodyData:(NSInteger)bytesWritten
|
||||||
totalBytesWritten:(NSInteger)totalBytesWritten
|
totalBytesWritten:(NSInteger)totalBytesWritten
|
||||||
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
|
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
|
||||||
{
|
{
|
||||||
if (self.uploadProgress) {
|
if (self.uploadProgress) {
|
||||||
|
|
@ -614,10 +614,10 @@ totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)connection:(NSURLConnection __unused *)connection
|
- (void)connection:(NSURLConnection __unused *)connection
|
||||||
didReceiveResponse:(NSURLResponse *)response
|
didReceiveResponse:(NSURLResponse *)response
|
||||||
{
|
{
|
||||||
self.response = response;
|
self.response = response;
|
||||||
|
|
||||||
[self.outputStream open];
|
[self.outputStream open];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -625,12 +625,12 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
didReceiveData:(NSData *)data
|
didReceiveData:(NSData *)data
|
||||||
{
|
{
|
||||||
self.totalBytesRead += [data length];
|
self.totalBytesRead += [data length];
|
||||||
|
|
||||||
if ([self.outputStream hasSpaceAvailable]) {
|
if ([self.outputStream hasSpaceAvailable]) {
|
||||||
const uint8_t *dataBuffer = (uint8_t *) [data bytes];
|
const uint8_t *dataBuffer = (uint8_t *) [data bytes];
|
||||||
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
|
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self.downloadProgress) {
|
if (self.downloadProgress) {
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
self.downloadProgress([data length], self.totalBytesRead, self.response.expectedContentLength);
|
self.downloadProgress([data length], self.totalBytesRead, self.response.expectedContentLength);
|
||||||
|
|
@ -640,28 +640,28 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
|
|
||||||
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
|
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
|
||||||
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
|
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
|
||||||
|
|
||||||
[self.outputStream close];
|
[self.outputStream close];
|
||||||
|
|
||||||
[self finish];
|
[self finish];
|
||||||
|
|
||||||
self.connection = nil;
|
self.connection = nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)connection:(NSURLConnection __unused *)connection
|
- (void)connection:(NSURLConnection __unused *)connection
|
||||||
didFailWithError:(NSError *)error
|
didFailWithError:(NSError *)error
|
||||||
{
|
{
|
||||||
self.error = error;
|
self.error = error;
|
||||||
|
|
||||||
[self.outputStream close];
|
[self.outputStream close];
|
||||||
|
|
||||||
[self finish];
|
[self finish];
|
||||||
|
|
||||||
self.connection = nil;
|
self.connection = nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
|
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
|
||||||
willCacheResponse:(NSCachedURLResponse *)cachedResponse
|
willCacheResponse:(NSCachedURLResponse *)cachedResponse
|
||||||
{
|
{
|
||||||
if (self.cacheResponse) {
|
if (self.cacheResponse) {
|
||||||
return self.cacheResponse(connection, cachedResponse);
|
return self.cacheResponse(connection, cachedResponse);
|
||||||
|
|
@ -669,8 +669,8 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
if ([self isCancelled]) {
|
if ([self isCancelled]) {
|
||||||
return nil;
|
return nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
return cachedResponse;
|
return cachedResponse;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -678,7 +678,7 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
|
|
||||||
- (id)initWithCoder:(NSCoder *)aDecoder {
|
- (id)initWithCoder:(NSCoder *)aDecoder {
|
||||||
NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
|
NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
|
||||||
|
|
||||||
self = [self initWithRequest:request];
|
self = [self initWithRequest:request];
|
||||||
if (!self) {
|
if (!self) {
|
||||||
return nil;
|
return nil;
|
||||||
|
|
@ -690,13 +690,13 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
self.error = [aDecoder decodeObjectForKey:@"error"];
|
self.error = [aDecoder decodeObjectForKey:@"error"];
|
||||||
self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
|
self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
|
||||||
self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
|
self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
|
||||||
|
|
||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
||||||
[self pause];
|
[self pause];
|
||||||
|
|
||||||
[aCoder encodeObject:self.request forKey:@"request"];
|
[aCoder encodeObject:self.request forKey:@"request"];
|
||||||
|
|
||||||
switch (self.state) {
|
switch (self.state) {
|
||||||
|
|
@ -708,7 +708,7 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
[aCoder encodeInteger:self.state forKey:@"state"];
|
[aCoder encodeInteger:self.state forKey:@"state"];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
[aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
|
[aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
|
||||||
[aCoder encodeObject:self.response forKey:@"response"];
|
[aCoder encodeObject:self.response forKey:@"response"];
|
||||||
[aCoder encodeObject:self.error forKey:@"error"];
|
[aCoder encodeObject:self.error forKey:@"error"];
|
||||||
|
|
@ -720,14 +720,14 @@ didReceiveResponse:(NSURLResponse *)response
|
||||||
|
|
||||||
- (id)copyWithZone:(NSZone *)zone {
|
- (id)copyWithZone:(NSZone *)zone {
|
||||||
AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
|
AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
|
||||||
|
|
||||||
operation.uploadProgress = self.uploadProgress;
|
operation.uploadProgress = self.uploadProgress;
|
||||||
operation.downloadProgress = self.downloadProgress;
|
operation.downloadProgress = self.downloadProgress;
|
||||||
operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace;
|
operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace;
|
||||||
operation.authenticationChallenge = self.authenticationChallenge;
|
operation.authenticationChallenge = self.authenticationChallenge;
|
||||||
operation.cacheResponse = self.cacheResponse;
|
operation.cacheResponse = self.cacheResponse;
|
||||||
operation.redirectResponse = self.redirectResponse;
|
operation.redirectResponse = self.redirectResponse;
|
||||||
|
|
||||||
return operation;
|
return operation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFXMLRequestOperation.h
|
// AFXMLRequestOperation.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -27,16 +27,16 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
|
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
|
||||||
|
|
||||||
## Acceptable Content Types
|
## Acceptable Content Types
|
||||||
|
|
||||||
By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
|
||||||
|
|
||||||
- `application/xml`
|
- `application/xml`
|
||||||
- `text/xml`
|
- `text/xml`
|
||||||
|
|
||||||
## Use With AFHTTPClient
|
## Use With AFHTTPClient
|
||||||
|
|
||||||
When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
|
When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback.
|
||||||
*/
|
*/
|
||||||
@interface AFXMLRequestOperation : AFHTTPRequestOperation
|
@interface AFXMLRequestOperation : AFHTTPRequestOperation
|
||||||
|
|
@ -59,11 +59,11 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
|
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
|
||||||
|
|
||||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation
|
@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 XML parser constructed with the response data of request.
|
@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 XML parser constructed with the response data of request.
|
||||||
@param failure A block object to be executed when the operation finishes unsuccessfully. 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 error that occurred.
|
@param failure A block object to be executed when the operation finishes unsuccessfully. 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 error that occurred.
|
||||||
|
|
||||||
@return A new XML request operation
|
@return A new XML request operation
|
||||||
*/
|
*/
|
||||||
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
|
|
@ -74,11 +74,11 @@
|
||||||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||||
/**
|
/**
|
||||||
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
|
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
|
||||||
|
|
||||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation
|
@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 XML document created from the response data of request.
|
@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 XML document 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 response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. 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 XML request operation
|
@return A new XML request operation
|
||||||
*/
|
*/
|
||||||
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// AFXMLRequestOperation.m
|
// AFXMLRequestOperation.m
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -29,7 +29,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
if (af_xml_request_operation_processing_queue == NULL) {
|
if (af_xml_request_operation_processing_queue == NULL) {
|
||||||
af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0);
|
af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
return af_xml_request_operation_processing_queue;
|
return af_xml_request_operation_processing_queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -62,7 +62,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
|
failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -74,7 +74,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
|
AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
|
||||||
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
|
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
|
||||||
if (success) {
|
if (success) {
|
||||||
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
|
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
|
||||||
success(operation.request, operation.response, XMLDocument);
|
success(operation.request, operation.response, XMLDocument);
|
||||||
}
|
}
|
||||||
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
|
||||||
|
|
@ -83,7 +83,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
failure(operation.request, operation.response, error, XMLDocument);
|
failure(operation.request, operation.response, error, XMLDocument);
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|
||||||
return requestOperation;
|
return requestOperation;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
@ -93,7 +93,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
|
if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
|
||||||
self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
|
self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responseXMLParser;
|
return _responseXMLParser;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -104,7 +104,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
|
self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error];
|
||||||
self.XMLError = error;
|
self.XMLError = error;
|
||||||
}
|
}
|
||||||
|
|
||||||
return _responseXMLDocument;
|
return _responseXMLDocument;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
@ -121,7 +121,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
|
|
||||||
- (void)cancel {
|
- (void)cancel {
|
||||||
[super cancel];
|
[super cancel];
|
||||||
|
|
||||||
self.responseXMLParser.delegate = nil;
|
self.responseXMLParser.delegate = nil;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -140,10 +140,10 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
{
|
{
|
||||||
#pragma clang diagnostic push
|
#pragma clang diagnostic push
|
||||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||||
self.completionBlock = ^ {
|
self.completionBlock = ^ {
|
||||||
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
|
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
|
||||||
NSXMLParser *XMLParser = self.responseXMLParser;
|
NSXMLParser *XMLParser = self.responseXMLParser;
|
||||||
|
|
||||||
if (self.error) {
|
if (self.error) {
|
||||||
if (failure) {
|
if (failure) {
|
||||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
|
|
@ -155,7 +155,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
||||||
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||||
success(self, XMLParser);
|
success(self, XMLParser);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,17 @@
|
||||||
// UIImageView+AFNetworking.h
|
// UIImageView+AFNetworking.h
|
||||||
//
|
//
|
||||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||||
//
|
//
|
||||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
// of this software and associated documentation files (the "Software"), to deal
|
// of this software and associated documentation files (the "Software"), to deal
|
||||||
// in the Software without restriction, including without limitation the rights
|
// in the Software without restriction, including without limitation the rights
|
||||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
// copies of the Software, and to permit persons to whom the Software is
|
// copies of the Software, and to permit persons to whom the Software is
|
||||||
// furnished to do so, subject to the following conditions:
|
// furnished to do so, subject to the following conditions:
|
||||||
//
|
//
|
||||||
// The above copyright notice and this permission notice shall be included in
|
// The above copyright notice and this permission notice shall be included in
|
||||||
// all copies or substantial portions of the Software.
|
// all copies or substantial portions of the Software.
|
||||||
//
|
//
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
|
@ -35,36 +35,36 @@
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||||
|
|
||||||
@discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
@discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||||
|
|
||||||
@param url The URL used for the image request.
|
@param url The URL used for the image request.
|
||||||
*/
|
*/
|
||||||
- (void)setImageWithURL:(NSURL *)url;
|
- (void)setImageWithURL:(NSURL *)url;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||||
|
|
||||||
@param url The URL used for the image request.
|
@param url The URL used for the image request.
|
||||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
||||||
|
|
||||||
@discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
@discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
|
||||||
*/
|
*/
|
||||||
- (void)setImageWithURL:(NSURL *)url
|
- (void)setImageWithURL:(NSURL *)url
|
||||||
placeholderImage:(UIImage *)placeholderImage;
|
placeholderImage:(UIImage *)placeholderImage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
|
||||||
|
|
||||||
@param urlRequest The URL request used for the image request.
|
@param urlRequest The URL request used for the image request.
|
||||||
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
|
||||||
@param success A block to be executed when the image request operation 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 sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
|
@param success A block to be executed when the image request operation 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 sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
|
||||||
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that 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 error object describing the network or parsing error that occurred.
|
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that 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 error object describing the network or parsing error that occurred.
|
||||||
|
|
||||||
@discussion If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed.
|
@discussion If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed.
|
||||||
*/
|
*/
|
||||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||||
placeholderImage:(UIImage *)placeholderImage
|
placeholderImage:(UIImage *)placeholderImage
|
||||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
|
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
|
||||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
|
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue