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
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
## Automatic Content Parsing
|
||||
|
||||
|
||||
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`.
|
||||
|
||||
|
||||
## Subclassing Notes
|
||||
|
||||
|
||||
In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
|
||||
|
||||
|
||||
## Methods to Override
|
||||
|
||||
|
||||
To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
|
||||
|
||||
|
||||
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`.
|
||||
|
||||
|
||||
## Default Headers
|
||||
|
||||
|
||||
By default, `AFHTTPClient` sets the following HTTP headers:
|
||||
|
||||
|
||||
- `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8`
|
||||
- `User-Agent: (generated user agent)`
|
||||
|
||||
|
||||
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
|
||||
|
||||
|
||||
## URL Construction Using Relative Paths
|
||||
|
||||
|
||||
Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact:
|
||||
|
||||
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
|
||||
|
||||
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"];
|
||||
[NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo
|
||||
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz
|
||||
[NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo
|
||||
|
|
@ -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.
|
||||
|
||||
## NSCoding / NSCopying Conformance
|
||||
|
||||
|
||||
`AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:
|
||||
|
||||
|
||||
- Archives and copies of HTTP clients will be initialized with an empty operation queue.
|
||||
- NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.
|
||||
*/
|
||||
|
|
@ -80,15 +80,15 @@ typedef enum {
|
|||
AFNetworkReachabilityStatusReachableViaWiFi = 2,
|
||||
} AFNetworkReachabilityStatus;
|
||||
#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
|
||||
|
||||
#ifndef __UTTYPE__
|
||||
#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.
|
||||
#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.
|
||||
#endif
|
||||
#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.
|
||||
#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.
|
||||
#endif
|
||||
#endif
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@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;
|
||||
|
|
@ -131,7 +131,7 @@ typedef enum {
|
|||
/**
|
||||
The reachability status from the device to the current `baseURL` of the `AFHTTPClient`.
|
||||
|
||||
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
@warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;
|
||||
|
|
@ -143,20 +143,20 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Creates and initializes an `AFHTTPClient` object with the specified base URL.
|
||||
|
||||
|
||||
@param url The base URL for the HTTP client. This argument must not be `nil`.
|
||||
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
+ (instancetype)clientWithBaseURL:(NSURL *)url;
|
||||
|
||||
/**
|
||||
Initializes an `AFHTTPClient` object with the specified base URL.
|
||||
|
||||
|
||||
@param url The base URL for the HTTP client. This argument must not be `nil`.
|
||||
|
||||
|
||||
@discussion This is the designated initializer.
|
||||
|
||||
|
||||
@return The newly-initialized HTTP client
|
||||
*/
|
||||
- (id)initWithBaseURL:(NSURL *)url;
|
||||
|
|
@ -167,9 +167,9 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Sets a callback to be executed when the network availability of the `baseURL` host changes.
|
||||
|
||||
|
||||
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
|
||||
|
||||
|
||||
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@param operationClass The subclass of `AFHTTPRequestOperation` to register
|
||||
|
||||
|
||||
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`.
|
||||
|
||||
|
||||
@discussion When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.
|
||||
*/
|
||||
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
|
||||
|
|
@ -194,7 +194,7 @@ typedef enum {
|
|||
/**
|
||||
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;
|
||||
|
||||
|
|
@ -204,16 +204,16 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Returns the value for the HTTP headers set in request objects created by the HTTP client.
|
||||
|
||||
|
||||
@param header The HTTP header to return the default value for
|
||||
|
||||
|
||||
@return The default value for the HTTP header, or `nil` if unspecified
|
||||
*/
|
||||
- (NSString *)defaultValueForHeader:(NSString *)header;
|
||||
|
||||
/**
|
||||
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
|
||||
|
||||
|
||||
@param header The HTTP header to set a default value for
|
||||
@param value The value set as default for the specified header, or `nil
|
||||
*/
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@param username The HTTP basic auth username
|
||||
@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.
|
||||
|
||||
|
||||
@param token The authentication token
|
||||
*/
|
||||
- (void)setAuthorizationHeaderWithToken:(NSString *)token;
|
||||
|
|
@ -248,7 +248,7 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Set the default URL credential to be set for request operations.
|
||||
|
||||
|
||||
@param credential The URL credential
|
||||
*/
|
||||
- (void)setDefaultCredential:(NSURLCredential *)credential;
|
||||
|
|
@ -259,29 +259,29 @@ typedef enum {
|
|||
|
||||
/**
|
||||
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.
|
||||
|
||||
|
||||
@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 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
|
||||
path:(NSString *)path
|
||||
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
|
||||
path:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters;
|
||||
|
||||
/**
|
||||
Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2
|
||||
|
||||
|
||||
@param method The HTTP method for the request. 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 parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.
|
||||
|
||||
|
||||
@discussion 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
|
||||
*/
|
||||
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
|
||||
|
|
@ -295,9 +295,9 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Creates an `AFHTTPRequestOperation`.
|
||||
|
||||
|
||||
In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
|
||||
|
||||
|
||||
@param 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 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.
|
||||
|
||||
|
||||
@param operation The HTTP request operation to be enqueued.
|
||||
*/
|
||||
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
|
||||
|
||||
/**
|
||||
Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
|
||||
|
||||
@param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
|
||||
|
||||
@param 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.
|
||||
|
||||
|
||||
@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;
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@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 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.
|
||||
*/
|
||||
- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
|
||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||
completionBlock:(void (^)(NSArray *operations))completionBlock;
|
||||
|
||||
/**
|
||||
Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
|
||||
|
||||
|
||||
@param operations The request operations used to be batched and enqueued.
|
||||
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
|
||||
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
|
||||
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
|
||||
*/
|
||||
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
|
||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
|
||||
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
|
||||
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.
|
||||
|
||||
|
||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
||||
@param parameters The parameters to be encoded and appended as the query string for the request URL.
|
||||
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||
|
||||
|
||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||
*/
|
||||
- (void)getPath:(NSString *)path
|
||||
|
|
@ -376,61 +376,61 @@ typedef enum {
|
|||
|
||||
/**
|
||||
Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue.
|
||||
|
||||
|
||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
||||
@param parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||
|
||||
|
||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||
*/
|
||||
- (void)postPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
- (void)postPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue.
|
||||
|
||||
|
||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
||||
@param parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||
|
||||
|
||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||
*/
|
||||
- (void)putPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
- (void)putPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue.
|
||||
|
||||
|
||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
||||
@param parameters The parameters to be encoded and appended as the query string for the request URL.
|
||||
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||
|
||||
|
||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||
*/
|
||||
- (void)deletePath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
- (void)deletePath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||
|
||||
/**
|
||||
Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue.
|
||||
|
||||
|
||||
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
|
||||
@param parameters The parameters to be encoded and set in the request HTTP body.
|
||||
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.
|
||||
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred.
|
||||
|
||||
|
||||
@see -HTTPRequestOperationWithRequest:success:failure:
|
||||
*/
|
||||
- (void)patchPath:(NSString *)path
|
||||
parameters:(NSDictionary *)parameters
|
||||
parameters:(NSDictionary *)parameters
|
||||
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
|
||||
@end
|
||||
|
|
@ -441,54 +441,54 @@ typedef enum {
|
|||
|
||||
/**
|
||||
### 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 {
|
||||
AFNetworkReachabilityStatusUnknown,
|
||||
AFNetworkReachabilityStatusNotReachable,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi,
|
||||
AFNetworkReachabilityStatusUnknown,
|
||||
AFNetworkReachabilityStatusNotReachable,
|
||||
AFNetworkReachabilityStatusReachableViaWWAN,
|
||||
AFNetworkReachabilityStatusReachableViaWiFi,
|
||||
}
|
||||
|
||||
`AFNetworkReachabilityStatusUnknown`
|
||||
The `baseURL` host reachability is not known.
|
||||
|
||||
|
||||
`AFNetworkReachabilityStatusUnknown`
|
||||
The `baseURL` host reachability is not known.
|
||||
|
||||
`AFNetworkReachabilityStatusNotReachable`
|
||||
The `baseURL` host cannot be reached.
|
||||
|
||||
The `baseURL` host cannot be reached.
|
||||
|
||||
`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`
|
||||
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
|
||||
|
||||
|
||||
Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.
|
||||
|
||||
|
||||
`AFNetworkingReachabilityNotificationStatusItem`
|
||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||
|
||||
A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
|
||||
The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
|
||||
|
||||
### Parameter Encoding
|
||||
|
||||
|
||||
The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values.
|
||||
|
||||
enum {
|
||||
AFFormURLParameterEncoding,
|
||||
AFJSONParameterEncoding,
|
||||
AFPropertyListParameterEncoding,
|
||||
AFFormURLParameterEncoding,
|
||||
AFJSONParameterEncoding,
|
||||
AFPropertyListParameterEncoding,
|
||||
}
|
||||
|
||||
|
||||
`AFFormURLParameterEncoding`
|
||||
Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. 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`
|
||||
Parameters are encoded into JSON in the message body.
|
||||
|
||||
`AFPropertyListParameterEncoding`
|
||||
Parameters are encoded into a property list in the message body.
|
||||
Parameters are encoded into JSON in the message body.
|
||||
|
||||
`AFPropertyListParameterEncoding`
|
||||
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.
|
||||
|
||||
|
||||
@param parameters The parameters used to construct the query string
|
||||
@param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs.
|
||||
|
||||
|
||||
@discussion Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&".
|
||||
|
||||
|
||||
If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component.
|
||||
|
||||
|
||||
@return A percent-escaped query string
|
||||
*/
|
||||
extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding);
|
||||
|
|
@ -516,7 +516,7 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
|
|||
/**
|
||||
Posted when network reachability changes.
|
||||
This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.
|
||||
|
||||
|
||||
@warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
|
||||
*/
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@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 error If an error occurs, upon return contains an `NSError` object that describes the problem.
|
||||
|
||||
|
||||
@return `YES` if the file data was successfully appended, otherwise `NO`.
|
||||
|
||||
|
||||
@discussion The filename and MIME type for this data in the form will be automatically generated, using `NSURLResponse` `-suggestedFilename` and `-MIMEType`, respectively.
|
||||
*/
|
||||
- (BOOL)appendPartWithFileURL:(NSURL *)fileURL
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@param data The data to be encoded and appended to the form data.
|
||||
@param name The name to be associated with the specified data. This parameter must not be `nil`.
|
||||
@param filename The filename to be associated with the specified data. This parameter must not be `nil`.
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@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`.
|
||||
*/
|
||||
|
|
@ -574,7 +574,7 @@ extern NSTimeInterval const kAFUploadStream3GSuggestedDelay;
|
|||
|
||||
/**
|
||||
Appends HTTP headers, followed by the encoded data and the multipart form boundary.
|
||||
|
||||
|
||||
@param headers The HTTP headers to be appended to the form data.
|
||||
@param body The data to be encoded and appended to the form data.
|
||||
*/
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@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.
|
||||
|
||||
|
||||
@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
|
||||
|
|
|
|||
|
|
@ -28,15 +28,15 @@
|
|||
#import <Availability.h>
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
#import <netinet/in.h>
|
||||
#import <netinet6/in6.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <netdb.h>
|
||||
#endif
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
|
|
@ -55,10 +55,10 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) {
|
|||
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
|
||||
NSUInteger length = [data length];
|
||||
NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
|
||||
|
||||
|
||||
uint8_t *input = (uint8_t *)[data bytes];
|
||||
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
|
||||
|
||||
|
||||
for (NSUInteger i = 0; i < length; i += 3) {
|
||||
NSUInteger value = 0;
|
||||
for (NSUInteger j = i; j < (i + 3); j++) {
|
||||
|
|
@ -67,23 +67,23 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) {
|
|||
value |= (0xFF & input[j]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
|
||||
NSUInteger idx = (i / 3) * 4;
|
||||
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
|
||||
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
|
||||
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
|
||||
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
|
||||
}
|
||||
|
||||
|
||||
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
|
||||
}
|
||||
|
||||
static NSString * AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
|
||||
static NSString * const kAFCharactersToBeEscaped = @":/?&=;+!@#$()~'";
|
||||
static NSString * const kAFCharactersToLeaveUnescaped = @"[].";
|
||||
|
||||
|
||||
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) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.field = field;
|
||||
self.value = value;
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -134,7 +134,7 @@ NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSS
|
|||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||
[mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]];
|
||||
}
|
||||
|
||||
|
||||
return [mutablePairs componentsJoinedByString:@"&"];
|
||||
}
|
||||
|
||||
|
|
@ -144,7 +144,7 @@ NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
|
|||
|
||||
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
||||
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
|
||||
|
||||
|
||||
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
|
||||
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)];
|
||||
|
|
@ -162,7 +162,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
|||
} else {
|
||||
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
|
||||
}
|
||||
|
||||
|
||||
return mutableQueryStringComponents;
|
||||
}
|
||||
|
||||
|
|
@ -213,45 +213,45 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
|||
|
||||
- (id)initWithBaseURL:(NSURL *)url {
|
||||
NSParameterAssert(url);
|
||||
|
||||
|
||||
self = [super init];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
// Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected
|
||||
if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) {
|
||||
url = [url URLByAppendingPathComponent:@""];
|
||||
}
|
||||
|
||||
|
||||
self.baseURL = url;
|
||||
|
||||
|
||||
self.stringEncoding = NSUTF8StringEncoding;
|
||||
self.parameterEncoding = AFFormURLParameterEncoding;
|
||||
|
||||
|
||||
self.registeredHTTPOperationClassNames = [NSMutableArray array];
|
||||
|
||||
|
||||
self.defaultHeaders = [NSMutableDictionary dictionary];
|
||||
|
||||
|
||||
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
|
||||
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
|
||||
[self setDefaultHeader:@"Accept-Language" value:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes]];
|
||||
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
|
||||
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]];
|
||||
#elif 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]]];
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef _SYSTEMCONFIGURATION_H
|
||||
self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown;
|
||||
[self startMonitoringNetworkReachability];
|
||||
#endif
|
||||
|
||||
|
||||
self.operationQueue = [[NSOperationQueue alloc] init];
|
||||
[self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -271,7 +271,7 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
|
|||
static BOOL AFURLHostIsIPAddress(NSURL *url) {
|
||||
struct sockaddr_in sa_in;
|
||||
struct sockaddr_in6 sa_in6;
|
||||
|
||||
|
||||
return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1);
|
||||
}
|
||||
|
||||
|
|
@ -279,7 +279,7 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork
|
|||
BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0);
|
||||
BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0);
|
||||
BOOL isNetworkReachable = (isReachable && !needsConnection);
|
||||
|
||||
|
||||
AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown;
|
||||
if (isNetworkReachable == NO) {
|
||||
status = AFNetworkReachabilityStatusNotReachable;
|
||||
|
|
@ -292,7 +292,7 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork
|
|||
else {
|
||||
status = AFNetworkReachabilityStatusReachableViaWiFi;
|
||||
}
|
||||
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
|
|
@ -302,7 +302,7 @@ static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused targ
|
|||
if (block) {
|
||||
block(status);
|
||||
}
|
||||
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[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 {
|
||||
[self stopMonitoringNetworkReachability];
|
||||
|
||||
|
||||
if (!self.baseURL) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
|
||||
|
||||
|
||||
if (!self.networkReachability) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
__weak __typeof(&*self)weakSelf = self;
|
||||
AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {
|
||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||
if (!strongSelf) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
strongSelf.networkReachabilityStatus = status;
|
||||
if (strongSelf.networkReachabilityStatusBlock) {
|
||||
strongSelf.networkReachabilityStatusBlock(status);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL};
|
||||
SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context);
|
||||
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
|
||||
|
||||
|
||||
/* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered.
|
||||
*/
|
||||
if (AFURLHostIsIPAddress(self.baseURL)) {
|
||||
|
|
@ -379,11 +379,11 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSString *className = NSStringFromClass(operationClass);
|
||||
[self.registeredHTTPOperationClassNames removeObject:className];
|
||||
[self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
|
@ -422,16 +422,16 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
parameters:(NSDictionary *)parameters
|
||||
{
|
||||
NSParameterAssert(method);
|
||||
|
||||
|
||||
if (!path) {
|
||||
path = @"";
|
||||
}
|
||||
|
||||
|
||||
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL];
|
||||
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
|
||||
[request setHTTPMethod:method];
|
||||
[request setAllHTTPHeaderFields:self.defaultHeaders];
|
||||
|
||||
|
||||
if (parameters) {
|
||||
if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) {
|
||||
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
|
||||
|
|
@ -439,7 +439,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
} else {
|
||||
NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
|
||||
NSError *error = nil;
|
||||
|
||||
|
||||
switch (self.parameterEncoding) {
|
||||
case AFFormURLParameterEncoding:;
|
||||
[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]];
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
if (error) {
|
||||
NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
|
|
@ -471,11 +471,11 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
{
|
||||
NSParameterAssert(method);
|
||||
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
|
||||
|
||||
|
||||
NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil];
|
||||
|
||||
|
||||
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding];
|
||||
|
||||
|
||||
if (parameters) {
|
||||
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
|
||||
NSData *data = nil;
|
||||
|
|
@ -486,17 +486,17 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
} else {
|
||||
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
|
||||
}
|
||||
|
||||
|
||||
if (data) {
|
||||
[formData appendPartWithFormData:data name:[pair.field description]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (block) {
|
||||
block(formData);
|
||||
}
|
||||
|
||||
|
||||
return [formData requestByFinalizingMultipartFormData];
|
||||
}
|
||||
|
||||
|
|
@ -513,15 +513,15 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
operation = [(AFHTTPRequestOperation *)[op_class alloc] initWithRequest:urlRequest];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!operation) {
|
||||
operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
|
||||
}
|
||||
|
||||
|
||||
[operation setCompletionBlockWithSuccess:success failure:failure];
|
||||
|
||||
operation.credential = self.defaultCredential;
|
||||
|
||||
|
||||
return operation;
|
||||
}
|
||||
|
||||
|
|
@ -535,15 +535,15 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
path:(NSString *)path
|
||||
{
|
||||
NSString *URLStringToMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] absoluteString];
|
||||
|
||||
|
||||
for (NSOperation *operation in [self.operationQueue operations]) {
|
||||
if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]];
|
||||
BOOL hasMatchingURL = [[[[(AFHTTPRequestOperation *)operation request] URL] absoluteString] isEqualToString:URLStringToMatched];
|
||||
|
||||
|
||||
if (hasMatchingMethod && hasMatchingURL) {
|
||||
[operation cancel];
|
||||
}
|
||||
|
|
@ -559,7 +559,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
|
||||
[mutableOperations addObject:operation];
|
||||
}
|
||||
|
||||
|
||||
[self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
|
||||
}
|
||||
|
||||
|
|
@ -578,7 +578,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
dispatch_release(dispatchGroup);
|
||||
#endif
|
||||
}];
|
||||
|
||||
|
||||
for (AFHTTPRequestOperation *operation in operations) {
|
||||
AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy];
|
||||
__weak AFHTTPRequestOperation *weakOperation = operation;
|
||||
|
|
@ -588,22 +588,22 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
if (originalCompletionBlock) {
|
||||
originalCompletionBlock();
|
||||
}
|
||||
|
||||
|
||||
__block NSUInteger numberOfFinishedOperations = 0;
|
||||
[operations enumerateObjectsUsingBlock:^(id obj, __unused NSUInteger idx, __unused BOOL *stop) {
|
||||
if ([(NSOperation *)obj isFinished]) {
|
||||
numberOfFinishedOperations++;
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
if (progressBlock) {
|
||||
progressBlock(numberOfFinishedOperations, [operations count]);
|
||||
}
|
||||
|
||||
|
||||
dispatch_group_leave(dispatchGroup);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
dispatch_group_enter(dispatchGroup);
|
||||
[batchedOperation addDependency:operation];
|
||||
}
|
||||
|
|
@ -667,17 +667,17 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
|
||||
- (id)initWithCoder:(NSCoder *)aDecoder {
|
||||
NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"];
|
||||
|
||||
|
||||
self = [self initWithBaseURL:baseURL];
|
||||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"];
|
||||
self.parameterEncoding = [aDecoder decodeIntegerForKey:@"parameterEncoding"];
|
||||
self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"];
|
||||
self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -693,7 +693,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) {
|
|||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL];
|
||||
|
||||
|
||||
HTTPClient.stringEncoding = self.stringEncoding;
|
||||
HTTPClient.parameterEncoding = self.parameterEncoding;
|
||||
HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames copyWithZone:zone];
|
||||
|
|
@ -786,11 +786,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.request = urlRequest;
|
||||
self.stringEncoding = encoding;
|
||||
self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -800,27 +800,27 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
{
|
||||
NSParameterAssert(fileURL);
|
||||
NSParameterAssert(name);
|
||||
|
||||
|
||||
if (![fileURL isFileURL]) {
|
||||
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
||||
if (error != NULL) {
|
||||
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
}
|
||||
|
||||
|
||||
return NO;
|
||||
} else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) {
|
||||
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey];
|
||||
if (error != NULL) {
|
||||
*error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo];
|
||||
}
|
||||
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, [fileURL lastPathComponent]] forKey:@"Content-Disposition"];
|
||||
[mutableHeaders setValue:AFContentTypeForPathExtension([fileURL pathExtension]) forKey:@"Content-Type"];
|
||||
|
||||
|
||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = mutableHeaders;
|
||||
|
|
@ -828,9 +828,9 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
|
||||
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil];
|
||||
bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
|
||||
|
||||
|
||||
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
|
@ -842,11 +842,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
NSParameterAssert(name);
|
||||
NSParameterAssert(fileName);
|
||||
NSParameterAssert(mimeType);
|
||||
|
||||
|
||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"];
|
||||
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
|
||||
|
||||
|
||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||
}
|
||||
|
||||
|
|
@ -854,10 +854,10 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
name:(NSString *)name
|
||||
{
|
||||
NSParameterAssert(name);
|
||||
|
||||
|
||||
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
|
||||
[mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"];
|
||||
|
||||
|
||||
[self appendPartWithHeaders:mutableHeaders body:data];
|
||||
}
|
||||
|
||||
|
|
@ -865,13 +865,13 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
body:(NSData *)body
|
||||
{
|
||||
NSParameterAssert(body);
|
||||
|
||||
|
||||
AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init];
|
||||
bodyPart.stringEncoding = self.stringEncoding;
|
||||
bodyPart.headers = headers;
|
||||
bodyPart.bodyContentLength = [body length];
|
||||
bodyPart.body = body;
|
||||
|
||||
|
||||
[self.bodyStream appendHTTPBodyPart:bodyPart];
|
||||
}
|
||||
|
||||
|
|
@ -886,14 +886,14 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
if ([self.bodyStream isEmpty]) {
|
||||
return self.request;
|
||||
}
|
||||
|
||||
|
||||
// Reset the initial and final boundaries to ensure correct Content-Length
|
||||
[self.bodyStream setInitialAndFinalBoundaries];
|
||||
|
||||
|
||||
[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 setHTTPBodyStream:self.bodyStream];
|
||||
|
||||
|
||||
return self.request;
|
||||
}
|
||||
|
||||
|
|
@ -926,11 +926,11 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.stringEncoding = encoding;
|
||||
self.HTTPBodyParts = [NSMutableArray array];
|
||||
self.numberOfBytesInPacket = NSIntegerMax;
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -940,7 +940,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
bodyPart.hasInitialBoundary = NO;
|
||||
bodyPart.hasFinalBoundary = NO;
|
||||
}
|
||||
|
||||
|
||||
[[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES];
|
||||
[[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
|
||||
}
|
||||
|
|
@ -963,7 +963,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
return 0;
|
||||
}
|
||||
NSInteger bytesRead = 0;
|
||||
|
||||
|
||||
while ((NSUInteger)bytesRead < MIN(length, self.numberOfBytesInPacket)) {
|
||||
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
|
||||
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
|
||||
|
|
@ -995,9 +995,9 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
if (self.streamStatus == NSStreamStatusOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
self.streamStatus = NSStreamStatusOpen;
|
||||
|
||||
|
||||
[self setInitialAndFinalBoundaries];
|
||||
self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
|
||||
}
|
||||
|
|
@ -1029,7 +1029,7 @@ NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
|
|||
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
|
||||
length += [bodyPart contentLength];
|
||||
}
|
||||
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
|
|
@ -1099,9 +1099,9 @@ typedef enum {
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
[self transitionToNextPhase];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -1130,24 +1130,24 @@ typedef enum {
|
|||
[headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
|
||||
}
|
||||
[headerString appendString:kAFMultipartFormCRLF];
|
||||
|
||||
|
||||
return [NSString stringWithString:headerString];
|
||||
}
|
||||
|
||||
- (unsigned long long)contentLength {
|
||||
unsigned long long length = 0;
|
||||
|
||||
|
||||
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
||||
length += [encapsulationBoundaryData length];
|
||||
|
||||
|
||||
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
||||
length += [headersData length];
|
||||
|
||||
|
||||
length += _bodyContentLength;
|
||||
|
||||
|
||||
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
||||
length += [closingBoundaryData length];
|
||||
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
|
|
@ -1156,7 +1156,7 @@ typedef enum {
|
|||
if (_phase == AFFinalBoundaryPhase) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
switch (self.inputStream.streamStatus) {
|
||||
case NSStreamStatusNotOpen:
|
||||
case NSStreamStatusOpening:
|
||||
|
|
@ -1176,27 +1176,27 @@ typedef enum {
|
|||
maxLength:(NSUInteger)length
|
||||
{
|
||||
NSInteger bytesRead = 0;
|
||||
|
||||
|
||||
if (_phase == AFEncapsulationBoundaryPhase) {
|
||||
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding];
|
||||
bytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||
}
|
||||
|
||||
|
||||
if (_phase == AFHeaderPhase) {
|
||||
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
|
||||
bytesRead += [self readData:headersData intoBuffer:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||
}
|
||||
|
||||
|
||||
if (_phase == AFBodyPhase) {
|
||||
if ([self.inputStream hasBytesAvailable]) {
|
||||
bytesRead += [self.inputStream read:&buffer[bytesRead] maxLength:(length - (NSUInteger)bytesRead)];
|
||||
}
|
||||
|
||||
|
||||
if (![self.inputStream hasBytesAvailable]) {
|
||||
[self transitionToNextPhase];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (_phase == AFFinalBoundaryPhase) {
|
||||
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]);
|
||||
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));
|
||||
[data getBytes:buffer range:range];
|
||||
|
||||
|
||||
_phaseReadOffset += range.length;
|
||||
|
||||
|
||||
if (((NSUInteger)_phaseReadOffset) >= [data length]) {
|
||||
[self transitionToNextPhase];
|
||||
}
|
||||
|
||||
|
||||
return (NSInteger)range.length;
|
||||
}
|
||||
|
||||
|
|
@ -1226,7 +1226,7 @@ typedef enum {
|
|||
[self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES];
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
switch (_phase) {
|
||||
case AFEncapsulationBoundaryPhase:
|
||||
_phase = AFHeaderPhase;
|
||||
|
|
@ -1246,7 +1246,7 @@ typedef enum {
|
|||
break;
|
||||
}
|
||||
_phaseReadOffset = 0;
|
||||
|
||||
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFHTTPRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -51,12 +51,12 @@
|
|||
*/
|
||||
@property (nonatomic, readonly) BOOL hasAcceptableContentType;
|
||||
|
||||
/**
|
||||
/**
|
||||
The callback dispatch queue on success. If `NULL` (default), the main queue is used.
|
||||
*/
|
||||
@property (nonatomic, assign) dispatch_queue_t successCallbackQueue;
|
||||
|
||||
/**
|
||||
/**
|
||||
The callback dispatch queue on failure. If `NULL` (default), the main queue is used.
|
||||
*/
|
||||
@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue;
|
||||
|
|
@ -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
|
||||
|
||||
|
||||
By default, this is the range 200 to 299, inclusive.
|
||||
*/
|
||||
+ (NSIndexSet *)acceptableStatusCodes;
|
||||
|
||||
/**
|
||||
Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants.
|
||||
|
||||
|
||||
@param statusCodes The status codes to be added to the set of acceptable HTTP status codes
|
||||
*/
|
||||
+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes;
|
||||
|
||||
/**
|
||||
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
|
||||
|
||||
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
|
||||
|
||||
By default, this is `nil`.
|
||||
*/
|
||||
+ (NSSet *)acceptableContentTypes;
|
||||
|
|
@ -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`.
|
||||
|
||||
|
||||
@param urlRequest The request that is determined to be supported or not supported for this class.
|
||||
*/
|
||||
+ (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.
|
||||
|
||||
|
||||
@param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request.
|
||||
@param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request.
|
||||
|
||||
|
||||
@discussion This method should be overridden in subclasses in order to specify the response object passed into the success block.
|
||||
*/
|
||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFHTTPRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -25,12 +25,12 @@
|
|||
|
||||
// Workaround for change in imp_implementationWithBlock() with Xcode 4.5
|
||||
#if defined(__IPHONE_6_0) || defined(__MAC_10_8)
|
||||
#define AF_CAST_TO_BLOCK id
|
||||
#define AF_CAST_TO_BLOCK id
|
||||
#else
|
||||
#define AF_CAST_TO_BLOCK __bridge void *
|
||||
#define AF_CAST_TO_BLOCK __bridge void *
|
||||
#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 ignored "-Wstrict-selector-match"
|
||||
|
||||
|
|
@ -47,9 +47,9 @@ NSSet * AFContentTypesFromHTTPHeader(NSString *string) {
|
|||
if (parametersRange.location != NSNotFound) {
|
||||
mediaRange = [mediaRange substringToIndex:parametersRange.location];
|
||||
}
|
||||
|
||||
|
||||
mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
|
||||
|
||||
|
||||
if (mediaRange.length > 0) {
|
||||
[mutableContentTypes addObject:mediaRange];
|
||||
}
|
||||
|
|
@ -130,7 +130,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
#endif
|
||||
_successCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
|
||||
if (_failureCallbackQueue) {
|
||||
#if !OS_OBJECT_USE_OBJC
|
||||
dispatch_release(_failureCallbackQueue);
|
||||
|
|
@ -147,7 +147,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
|
||||
[userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey];
|
||||
[userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey];
|
||||
|
||||
|
||||
if (![self hasAcceptableStatusCode]) {
|
||||
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
||||
[userInfo setValue:[NSString stringWithFormat: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) {
|
||||
return self.HTTPError;
|
||||
} else {
|
||||
|
|
@ -189,7 +189,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
}
|
||||
|
||||
- (void)pause {
|
||||
unsigned long long offset = 0;
|
||||
unsigned long long offset = 0;
|
||||
if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) {
|
||||
offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue];
|
||||
} else {
|
||||
|
|
@ -202,7 +202,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
}
|
||||
[mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"];
|
||||
self.request = mutableURLRequest;
|
||||
|
||||
|
||||
[super pause];
|
||||
}
|
||||
|
||||
|
|
@ -210,7 +210,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
if (!self.response) {
|
||||
return NO;
|
||||
}
|
||||
|
||||
|
||||
NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200;
|
||||
return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode];
|
||||
}
|
||||
|
|
@ -219,14 +219,14 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
if (!self.response) {
|
||||
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".
|
||||
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html
|
||||
NSString *contentType = [self.response MIMEType];
|
||||
if (!contentType) {
|
||||
contentType = @"application/octet-stream";
|
||||
}
|
||||
|
||||
|
||||
return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType];
|
||||
}
|
||||
|
||||
|
|
@ -245,7 +245,7 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
#endif
|
||||
_successCallbackQueue = successCallbackQueue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue {
|
||||
|
|
@ -256,14 +256,14 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
#endif
|
||||
_failureCallbackQueue = NULL;
|
||||
}
|
||||
|
||||
|
||||
if (failureCallbackQueue) {
|
||||
#if !OS_OBJECT_USE_OBJC
|
||||
dispatch_retain(failureCallbackQueue);
|
||||
#endif
|
||||
_failureCallbackQueue = failureCallbackQueue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
|
||||
|
|
@ -320,17 +320,17 @@ static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL
|
|||
if ([[self class] isEqual:[AFHTTPRequestOperation class]]) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
|
||||
return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])];
|
||||
}
|
||||
|
||||
#pragma mark - NSURLConnectionDelegate
|
||||
|
||||
- (void)connection:(__unused NSURLConnection *)connection
|
||||
didReceiveResponse:(NSURLResponse *)response
|
||||
- (void)connection:(__unused NSURLConnection *)connection
|
||||
didReceiveResponse:(NSURLResponse *)response
|
||||
{
|
||||
self.response = (NSHTTPURLResponse *)response;
|
||||
|
||||
|
||||
// Set Content-Range header if status code of response is 206 (Partial Content)
|
||||
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7
|
||||
long long totalContentLength = self.response.expectedContentLength;
|
||||
|
|
@ -351,7 +351,7 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
} else {
|
||||
if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) {
|
||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||
|
||||
|
||||
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
||||
for (NSString *runLoopMode in self.runLoopModes) {
|
||||
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||
|
|
@ -359,7 +359,7 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
self.offsetContentLength = MAX(fileOffset, 0);
|
||||
self.totalContentLength = totalContentLength;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFImageRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -26,18 +26,18 @@
|
|||
#import <Availability.h>
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#endif
|
||||
|
||||
/**
|
||||
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
|
||||
|
||||
|
||||
## Acceptable Content Types
|
||||
|
||||
|
||||
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
|
||||
|
||||
|
||||
- `image/tiff`
|
||||
- `image/jpeg`
|
||||
- `image/gif`
|
||||
|
|
@ -69,28 +69,28 @@
|
|||
|
||||
/**
|
||||
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
|
||||
|
||||
|
||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
|
||||
@param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single arguments, the image created from the response data of the request.
|
||||
|
||||
|
||||
@return A new image request operation
|
||||
*/
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(UIImage *image))success;
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(NSImage *image))success;
|
||||
#endif
|
||||
|
||||
/**
|
||||
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
|
||||
|
||||
|
||||
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
|
||||
@param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image.
|
||||
@param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data.
|
||||
@param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation.
|
||||
|
||||
|
||||
@return A new image request operation
|
||||
*/
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFImageRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
if (af_image_request_operation_processing_queue == NULL) {
|
||||
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
|
||||
}
|
||||
|
||||
|
||||
return af_image_request_operation_processing_queue;
|
||||
}
|
||||
|
||||
|
|
@ -46,7 +46,7 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
#endif
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(UIImage *image))success
|
||||
{
|
||||
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];
|
||||
}
|
||||
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(NSImage *image))success
|
||||
{
|
||||
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);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
#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);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
#endif
|
||||
|
|
@ -136,11 +136,11 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
self.imageScale = [[UIScreen mainScreen] scale];
|
||||
#endif
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -149,10 +149,10 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
- (UIImage *)responseImage {
|
||||
if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) {
|
||||
UIImage *image = [UIImage imageWithData:self.responseData];
|
||||
|
||||
|
||||
self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation];
|
||||
}
|
||||
|
||||
|
||||
return _responseImage;
|
||||
}
|
||||
|
||||
|
|
@ -163,9 +163,9 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
return;
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
|
||||
_imageScale = imageScale;
|
||||
|
||||
|
||||
self.responseImage = nil;
|
||||
}
|
||||
#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 addRepresentation:bitimage];
|
||||
}
|
||||
|
||||
|
||||
return _responseImage;
|
||||
}
|
||||
#endif
|
||||
|
|
@ -193,8 +193,8 @@ static dispatch_queue_t image_request_operation_processing_queue() {
|
|||
dispatch_once(&onceToken, ^{
|
||||
_acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
|
||||
});
|
||||
|
||||
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
|
||||
|
||||
return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request];
|
||||
}
|
||||
|
||||
- (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);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
} else {
|
||||
if (success) {
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
UIImage *image = nil;
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@
|
|||
@return A new JSON request operation
|
||||
*/
|
||||
+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure;
|
||||
|
||||
@end
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFJSONRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
|||
if (af_json_request_operation_processing_queue == NULL) {
|
||||
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0);
|
||||
}
|
||||
|
||||
|
||||
return af_json_request_operation_processing_queue;
|
||||
}
|
||||
|
||||
|
|
@ -55,7 +55,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
|||
failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
|
||||
|
|
@ -74,10 +74,10 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
|||
NSData *JSONData = [self.responseString dataUsingEncoding:self.responseStringEncoding];
|
||||
self.responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:self.JSONReadingOptions error:&error];
|
||||
}
|
||||
|
||||
|
||||
self.JSONError = error;
|
||||
}
|
||||
|
||||
|
||||
return _responseJSON;
|
||||
}
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
|||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||
self.completionBlock = ^ {
|
||||
self.completionBlock = ^ {
|
||||
if (self.error) {
|
||||
if (failure) {
|
||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||
|
|
@ -114,7 +114,7 @@ static dispatch_queue_t json_request_operation_processing_queue() {
|
|||
} else {
|
||||
dispatch_async(json_request_operation_processing_queue(), ^{
|
||||
id JSON = self.responseJSON;
|
||||
|
||||
|
||||
if (self.JSONError) {
|
||||
if (failure) {
|
||||
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(), ^{
|
||||
success(self, JSON);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFNetworkActivityIndicatorManager.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
@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.
|
||||
*/
|
||||
@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.
|
||||
*/
|
||||
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
||||
@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible;
|
||||
|
||||
/**
|
||||
Returns the shared network activity indicator manager object for the system.
|
||||
|
||||
|
||||
@return The systemwide network activity indicator manager.
|
||||
*/
|
||||
+ (instancetype)sharedManager;
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFNetworkActivityIndicatorManager.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -48,7 +48,7 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
|
|||
dispatch_once(&oncePredicate, ^{
|
||||
_sharedManager = [[self alloc] init];
|
||||
});
|
||||
|
||||
|
||||
return _sharedManager;
|
||||
}
|
||||
|
||||
|
|
@ -61,18 +61,18 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17;
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self];
|
||||
|
||||
|
||||
[_activityIndicatorVisibilityTimer invalidate];
|
||||
|
||||
|
||||
}
|
||||
|
||||
- (void)updateNetworkActivityIndicatorVisibilityDelayed {
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFPropertyListRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -25,11 +25,11 @@
|
|||
|
||||
/**
|
||||
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
|
||||
|
||||
|
||||
## Acceptable Content Types
|
||||
|
||||
|
||||
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
|
||||
|
||||
|
||||
- `application/x-plist`
|
||||
*/
|
||||
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation
|
||||
|
|
@ -54,11 +54,11 @@
|
|||
|
||||
/**
|
||||
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 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.
|
||||
|
||||
|
||||
@return A new property list request operation
|
||||
*/
|
||||
+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFPropertyListRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -27,7 +27,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
|||
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);
|
||||
}
|
||||
|
||||
|
||||
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]);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
|
||||
|
|
@ -66,9 +66,9 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.propertyListReadOptions = NSPropertyListImmutable;
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -81,7 +81,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
|||
self.propertyListFormat = format;
|
||||
self.propertyListError = error;
|
||||
}
|
||||
|
||||
|
||||
return _responsePropertyList;
|
||||
}
|
||||
|
||||
|
|
@ -108,7 +108,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
|||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||
self.completionBlock = ^ {
|
||||
self.completionBlock = ^ {
|
||||
if (self.error) {
|
||||
if (failure) {
|
||||
dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{
|
||||
|
|
@ -118,7 +118,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() {
|
|||
} else {
|
||||
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
|
||||
id propertyList = self.responsePropertyList;
|
||||
|
||||
|
||||
if (self.propertyListError) {
|
||||
if (failure) {
|
||||
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(), ^{
|
||||
success(self, propertyList);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFURLConnectionOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -26,17 +26,17 @@
|
|||
|
||||
/**
|
||||
`AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods.
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
|
||||
|
||||
|
||||
- `connection:didReceiveResponse:`
|
||||
- `connection:didReceiveData:`
|
||||
- `connectionDidFinishLoading:`
|
||||
|
|
@ -47,30 +47,30 @@
|
|||
- `connection:didReceiveAuthenticationChallenge:`
|
||||
- `connectionShouldUseCredentialStorage:`
|
||||
- `connection:needNewBodyStream:`
|
||||
|
||||
|
||||
If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first.
|
||||
|
||||
|
||||
## 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`.
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
`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
|
||||
|
||||
|
||||
- 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.
|
||||
|
||||
|
||||
### 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.
|
||||
- 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.
|
||||
|
|
@ -110,7 +110,7 @@
|
|||
///----------------------------
|
||||
|
||||
/**
|
||||
The data received during the request.
|
||||
The data received during the request.
|
||||
*/
|
||||
@property (readonly, nonatomic, strong) NSData *responseData;
|
||||
|
||||
|
|
@ -121,8 +121,8 @@
|
|||
|
||||
/**
|
||||
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;
|
||||
|
||||
|
|
@ -133,14 +133,14 @@
|
|||
|
||||
/**
|
||||
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:`.
|
||||
*/
|
||||
@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
@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`.
|
||||
*/
|
||||
@property (nonatomic, strong) NSInputStream *inputStream;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
@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.
|
||||
|
||||
|
||||
@param urlRequest The request object to be used by the operation connection.
|
||||
|
||||
|
||||
@discussion This is the designated initializer.
|
||||
*/
|
||||
- (id)initWithRequest:(NSURLRequest *)urlRequest;
|
||||
|
|
@ -191,21 +191,21 @@
|
|||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
- (void)pause;
|
||||
|
||||
/**
|
||||
Whether the request operation is currently paused.
|
||||
|
||||
|
||||
@return `YES` if the operation is currently paused, otherwise `NO`.
|
||||
*/
|
||||
- (BOOL)isPaused;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
- (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.
|
||||
|
||||
@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)
|
||||
- (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.
|
||||
|
||||
|
||||
@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;
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
- (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:`.
|
||||
|
||||
|
||||
@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`.
|
||||
*/
|
||||
- (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:`.
|
||||
|
||||
|
||||
@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.
|
||||
*/
|
||||
- (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:`.
|
||||
|
||||
|
||||
@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;
|
||||
|
|
@ -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:`.
|
||||
|
||||
|
||||
@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;
|
||||
|
|
@ -286,28 +286,28 @@
|
|||
|
||||
/**
|
||||
## User info dictionary keys
|
||||
|
||||
|
||||
These keys may exist in the user info dictionary, in addition to those defined for NSError.
|
||||
|
||||
|
||||
- `NSString * const AFNetworkingOperationFailingURLRequestErrorKey`
|
||||
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
|
||||
|
||||
|
||||
### Constants
|
||||
|
||||
|
||||
`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`.
|
||||
|
||||
|
||||
`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`.
|
||||
|
||||
|
||||
## Error Domains
|
||||
|
||||
|
||||
The following error domain is predefined.
|
||||
|
||||
|
||||
- `NSString * const AFNetworkingErrorDomain`
|
||||
|
||||
|
||||
### Constants
|
||||
|
||||
|
||||
`AFNetworkingErrorDomain`
|
||||
AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFURLConnectionOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -23,7 +23,7 @@
|
|||
#import "AFURLConnectionOperation.h"
|
||||
|
||||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
#import <UIKit/UIKit.h>
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
#if !__has_feature(objc_arc)
|
||||
|
|
@ -167,19 +167,19 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
+ (NSThread *)networkRequestThread {
|
||||
static NSThread *_networkRequestThread = nil;
|
||||
static dispatch_once_t oncePredicate;
|
||||
|
||||
|
||||
dispatch_once(&oncePredicate, ^{
|
||||
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
|
||||
[_networkRequestThread start];
|
||||
});
|
||||
|
||||
|
||||
return _networkRequestThread;
|
||||
}
|
||||
|
||||
+ (NSArray *)pinnedCertificates {
|
||||
static NSArray *_pinnedCertificates = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
|
||||
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
|
||||
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
|
||||
|
|
@ -190,7 +190,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
}
|
||||
_pinnedCertificates = [[NSArray alloc] initWithArray:certificates];
|
||||
});
|
||||
|
||||
|
||||
return _pinnedCertificates;
|
||||
}
|
||||
|
||||
|
|
@ -199,20 +199,20 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
if (!self) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
self.lock = [[NSRecursiveLock alloc] init];
|
||||
self.lock.name = kAFNetworkingLockName;
|
||||
|
||||
|
||||
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
|
||||
|
||||
|
||||
self.request = urlRequest;
|
||||
|
||||
self.shouldUseCredentialStorage = YES;
|
||||
|
||||
|
||||
self.outputStream = [NSOutputStream outputStreamToMemory];
|
||||
|
||||
self.state = AFOperationReadyState;
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
|
|
@ -242,7 +242,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
__weak __typeof(&*self)weakSelf = self;
|
||||
[super setCompletionBlock:^ {
|
||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||
|
||||
|
||||
block();
|
||||
[strongSelf setCompletionBlock:nil];
|
||||
}];
|
||||
|
|
@ -266,7 +266,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
if (outputStream == _outputStream) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self willChangeValueForKey:@"outputStream"];
|
||||
if (_outputStream) {
|
||||
[_outputStream close];
|
||||
|
|
@ -278,19 +278,19 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
|
||||
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
|
||||
[self.lock lock];
|
||||
if (!self.backgroundTaskIdentifier) {
|
||||
if (!self.backgroundTaskIdentifier) {
|
||||
UIApplication *application = [UIApplication sharedApplication];
|
||||
__weak __typeof(&*self)weakSelf = self;
|
||||
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
|
||||
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
|
||||
|
||||
|
||||
if (handler) {
|
||||
handler();
|
||||
}
|
||||
|
||||
|
||||
if (strongSelf) {
|
||||
[strongSelf cancel];
|
||||
|
||||
|
||||
[application endBackgroundTask:strongSelf.backgroundTaskIdentifier];
|
||||
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
|
||||
}
|
||||
|
|
@ -329,13 +329,13 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
if (AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
|
||||
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
|
||||
NSString *newStateKey = AFKeyPathFromOperationState(state);
|
||||
|
||||
|
||||
[self willChangeValueForKey:newStateKey];
|
||||
[self willChangeValueForKey:oldStateKey];
|
||||
_state = state;
|
||||
[self didChangeValueForKey:oldStateKey];
|
||||
[self didChangeValueForKey:newStateKey];
|
||||
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
switch (state) {
|
||||
case AFOperationExecutingState:
|
||||
|
|
@ -358,7 +358,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
|
||||
}
|
||||
[self.lock unlock];
|
||||
|
||||
|
||||
return _responseString;
|
||||
}
|
||||
|
||||
|
|
@ -372,11 +372,11 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
self.responseStringEncoding = stringEncoding;
|
||||
}
|
||||
[self.lock unlock];
|
||||
|
||||
|
||||
return _responseStringEncoding;
|
||||
}
|
||||
|
||||
|
|
@ -384,17 +384,17 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
if ([self isPaused] || [self isFinished] || [self isCancelled]) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self.lock lock];
|
||||
|
||||
|
||||
if ([self isExecuting]) {
|
||||
[self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
||||
|
||||
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
self.state = AFOperationPausedState;
|
||||
|
||||
[self.lock unlock];
|
||||
|
|
@ -408,10 +408,10 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
if (![self isPaused]) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self.lock lock];
|
||||
self.state = AFOperationReadyState;
|
||||
|
||||
|
||||
[self start];
|
||||
[self.lock unlock];
|
||||
}
|
||||
|
|
@ -438,7 +438,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
[self.lock lock];
|
||||
if ([self isReady]) {
|
||||
self.state = AFOperationExecutingState;
|
||||
|
||||
|
||||
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
|
||||
}
|
||||
[self.lock unlock];
|
||||
|
|
@ -450,14 +450,14 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
[self finish];
|
||||
} else {
|
||||
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
|
||||
|
||||
|
||||
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
|
||||
for (NSString *runLoopMode in self.runLoopModes) {
|
||||
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
|
||||
}
|
||||
|
||||
[self.connection start];
|
||||
|
||||
[self.connection start];
|
||||
}
|
||||
[self.lock unlock];
|
||||
}
|
||||
|
|
@ -474,7 +474,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
[super cancel];
|
||||
[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.lock unlock];
|
||||
|
|
@ -489,7 +489,7 @@ static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperat
|
|||
|
||||
if (self.connection) {
|
||||
[self.connection cancel];
|
||||
|
||||
|
||||
// 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];
|
||||
}
|
||||
|
|
@ -505,7 +505,7 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
|
|||
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
|
||||
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
|
||||
NSData *certificateData = (__bridge_transfer NSData *)SecCertificateCopyData(certificate);
|
||||
|
||||
|
||||
if ([[[self class] pinnedCertificates] containsObject:certificateData]) {
|
||||
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
|
||||
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
||||
|
|
@ -516,7 +516,7 @@ willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challe
|
|||
}
|
||||
#endif
|
||||
|
||||
- (BOOL)connection:(NSURLConnection *)connection
|
||||
- (BOOL)connection:(NSURLConnection *)connection
|
||||
canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
||||
{
|
||||
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
||||
|
|
@ -524,7 +524,7 @@ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
|||
return YES;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
if (self.authenticationAgainstProtectionSpace) {
|
||||
return self.authenticationAgainstProtectionSpace(connection, protectionSpace);
|
||||
} else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
|
||||
|
|
@ -534,8 +534,8 @@ canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
|
|||
}
|
||||
}
|
||||
|
||||
- (void)connection:(NSURLConnection *)connection
|
||||
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||
- (void)connection:(NSURLConnection *)connection
|
||||
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
||||
{
|
||||
#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_
|
||||
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
|
||||
|
|
@ -543,7 +543,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
|||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
if (self.authenticationChallenge) {
|
||||
self.authenticationChallenge(connection, challenge);
|
||||
} else {
|
||||
|
|
@ -564,7 +564,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
|||
if (!credential) {
|
||||
credential = self.credential;
|
||||
}
|
||||
|
||||
|
||||
if (credential) {
|
||||
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
|
||||
} else {
|
||||
|
|
@ -603,7 +603,7 @@ didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
|
|||
|
||||
- (void)connection:(NSURLConnection __unused *)connection
|
||||
didSendBodyData:(NSInteger)bytesWritten
|
||||
totalBytesWritten:(NSInteger)totalBytesWritten
|
||||
totalBytesWritten:(NSInteger)totalBytesWritten
|
||||
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
|
||||
{
|
||||
if (self.uploadProgress) {
|
||||
|
|
@ -614,10 +614,10 @@ totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
|
|||
}
|
||||
|
||||
- (void)connection:(NSURLConnection __unused *)connection
|
||||
didReceiveResponse:(NSURLResponse *)response
|
||||
didReceiveResponse:(NSURLResponse *)response
|
||||
{
|
||||
self.response = response;
|
||||
|
||||
|
||||
[self.outputStream open];
|
||||
}
|
||||
|
||||
|
|
@ -625,12 +625,12 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
didReceiveData:(NSData *)data
|
||||
{
|
||||
self.totalBytesRead += [data length];
|
||||
|
||||
|
||||
if ([self.outputStream hasSpaceAvailable]) {
|
||||
const uint8_t *dataBuffer = (uint8_t *) [data bytes];
|
||||
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
|
||||
}
|
||||
|
||||
|
||||
if (self.downloadProgress) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
self.downloadProgress([data length], self.totalBytesRead, self.response.expectedContentLength);
|
||||
|
|
@ -640,28 +640,28 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
|
||||
- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
|
||||
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
|
||||
|
||||
|
||||
[self.outputStream close];
|
||||
|
||||
|
||||
[self finish];
|
||||
|
||||
self.connection = nil;
|
||||
}
|
||||
|
||||
- (void)connection:(NSURLConnection __unused *)connection
|
||||
didFailWithError:(NSError *)error
|
||||
{
|
||||
didFailWithError:(NSError *)error
|
||||
{
|
||||
self.error = error;
|
||||
|
||||
|
||||
[self.outputStream close];
|
||||
|
||||
|
||||
[self finish];
|
||||
|
||||
self.connection = nil;
|
||||
}
|
||||
|
||||
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
|
||||
willCacheResponse:(NSCachedURLResponse *)cachedResponse
|
||||
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
|
||||
willCacheResponse:(NSCachedURLResponse *)cachedResponse
|
||||
{
|
||||
if (self.cacheResponse) {
|
||||
return self.cacheResponse(connection, cachedResponse);
|
||||
|
|
@ -669,8 +669,8 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
if ([self isCancelled]) {
|
||||
return nil;
|
||||
}
|
||||
|
||||
return cachedResponse;
|
||||
|
||||
return cachedResponse;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -678,7 +678,7 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
|
||||
- (id)initWithCoder:(NSCoder *)aDecoder {
|
||||
NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"];
|
||||
|
||||
|
||||
self = [self initWithRequest:request];
|
||||
if (!self) {
|
||||
return nil;
|
||||
|
|
@ -690,13 +690,13 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
self.error = [aDecoder decodeObjectForKey:@"error"];
|
||||
self.responseData = [aDecoder decodeObjectForKey:@"responseData"];
|
||||
self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue];
|
||||
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)encodeWithCoder:(NSCoder *)aCoder {
|
||||
[self pause];
|
||||
|
||||
|
||||
[aCoder encodeObject:self.request forKey:@"request"];
|
||||
|
||||
switch (self.state) {
|
||||
|
|
@ -708,7 +708,7 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
[aCoder encodeInteger:self.state forKey:@"state"];
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
[aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"];
|
||||
[aCoder encodeObject:self.response forKey:@"response"];
|
||||
[aCoder encodeObject:self.error forKey:@"error"];
|
||||
|
|
@ -720,14 +720,14 @@ didReceiveResponse:(NSURLResponse *)response
|
|||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
|
||||
|
||||
|
||||
operation.uploadProgress = self.uploadProgress;
|
||||
operation.downloadProgress = self.downloadProgress;
|
||||
operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace;
|
||||
operation.authenticationChallenge = self.authenticationChallenge;
|
||||
operation.cacheResponse = self.cacheResponse;
|
||||
operation.redirectResponse = self.redirectResponse;
|
||||
|
||||
|
||||
return operation;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFXMLRequestOperation.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -27,16 +27,16 @@
|
|||
|
||||
/**
|
||||
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
|
||||
|
||||
|
||||
## 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:
|
||||
|
||||
|
||||
- `application/xml`
|
||||
- `text/xml`
|
||||
|
||||
|
||||
## 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.
|
||||
*/
|
||||
@interface AFXMLRequestOperation : AFHTTPRequestOperation
|
||||
|
|
@ -59,11 +59,11 @@
|
|||
|
||||
/**
|
||||
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 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.
|
||||
|
||||
|
||||
@return A new XML request operation
|
||||
*/
|
||||
+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
|
|
@ -74,11 +74,11 @@
|
|||
#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
|
||||
/**
|
||||
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 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.
|
||||
|
||||
|
||||
@return A new XML request operation
|
||||
*/
|
||||
+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// AFXMLRequestOperation.m
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -29,7 +29,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
|||
if (af_xml_request_operation_processing_queue == NULL) {
|
||||
af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0);
|
||||
}
|
||||
|
||||
|
||||
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]);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
|||
AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest];
|
||||
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) {
|
||||
if (success) {
|
||||
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
|
||||
NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument];
|
||||
success(operation.request, operation.response, XMLDocument);
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
}];
|
||||
|
||||
|
||||
return requestOperation;
|
||||
}
|
||||
#endif
|
||||
|
|
@ -93,7 +93,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
|||
if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) {
|
||||
self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData];
|
||||
}
|
||||
|
||||
|
||||
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.XMLError = error;
|
||||
}
|
||||
|
||||
|
||||
return _responseXMLDocument;
|
||||
}
|
||||
#endif
|
||||
|
|
@ -121,7 +121,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
|||
|
||||
- (void)cancel {
|
||||
[super cancel];
|
||||
|
||||
|
||||
self.responseXMLParser.delegate = nil;
|
||||
}
|
||||
|
||||
|
|
@ -140,10 +140,10 @@ static dispatch_queue_t xml_request_operation_processing_queue() {
|
|||
{
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-retain-cycles"
|
||||
self.completionBlock = ^ {
|
||||
self.completionBlock = ^ {
|
||||
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
|
||||
NSXMLParser *XMLParser = self.responseXMLParser;
|
||||
|
||||
|
||||
if (self.error) {
|
||||
if (failure) {
|
||||
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(), ^{
|
||||
success(self, XMLParser);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// UIImageView+AFNetworking.h
|
||||
//
|
||||
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
|
||||
//
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
|
|
@ -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.
|
||||
|
||||
|
||||
@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.
|
||||
*/
|
||||
- (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.
|
||||
|
||||
|
||||
@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.
|
||||
|
||||
|
||||
@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;
|
||||
|
||||
/**
|
||||
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 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 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.
|
||||
*/
|
||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
*/
|
||||
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
|
||||
placeholderImage:(UIImage *)placeholderImage
|
||||
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
|
||||
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue