Merge branch 'experimental-0.7' into experimental-mac

Conflicts:
	AFNetworking/AFHTTPRequestOperation.m
	AFNetworking/AFImageRequestOperation.h
	AFNetworking/AFImageRequestOperation.m
	AFNetworking/AFNetworkActivityIndicatorManager.m
This commit is contained in:
Mattt Thompson 2011-10-11 10:01:44 -05:00
commit 358ecb568c
20 changed files with 1357 additions and 673 deletions

View file

@ -21,10 +21,17 @@
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
@class AFHTTPRequestOperation;
@protocol AFHTTPClientOperation;
@protocol AFMultipartFormData; @protocol AFMultipartFormData;
typedef enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
} AFHTTPClientParameterEncoding;
/** /**
`AFHTTPClient` objects encapsulates the common patterns of communicating with an application, webservice, or API. It encapsulates persistent information, like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations. `AFHTTPClient` objects encapsulates the common patterns of communicating with an application, webservice, or API. It encapsulates persistent information, like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
@ -49,6 +56,8 @@
@private @private
NSURL *_baseURL; NSURL *_baseURL;
NSStringEncoding _stringEncoding; NSStringEncoding _stringEncoding;
AFHTTPClientParameterEncoding _parameterEncoding;
NSMutableArray *_registeredHTTPOperationClassNames;
NSMutableDictionary *_defaultHeaders; NSMutableDictionary *_defaultHeaders;
NSOperationQueue *_operationQueue; NSOperationQueue *_operationQueue;
} }
@ -67,6 +76,11 @@
*/ */
@property (nonatomic, assign) NSStringEncoding stringEncoding; @property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
*/
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
/** /**
The operation queue which manages operations enqueued by the HTTP client. The operation queue which manages operations enqueued by the HTTP client.
*/ */
@ -96,6 +110,12 @@
*/ */
- (id)initWithBaseURL:(NSURL *)url; - (id)initWithBaseURL:(NSURL *)url;
///----------------------------------
/// @name Managing HTTP Operations
///----------------------------------
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
///---------------------------------- ///----------------------------------
/// @name Managing HTTP Header Values /// @name Managing HTTP Header Values
///---------------------------------- ///----------------------------------
@ -183,9 +203,12 @@
@param success A block object to be executed when the request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is an object created from the response data of request. @param success A block object to be executed when the request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is an object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a single argument, which is the `NSError` object describing the network or parsing error that occurred. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a single argument, which is the `NSError` object describing the network or parsing error that occurred.
*/ */
- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)request - (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(id object))success success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure;
/**
*/
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
///--------------------------------- ///---------------------------------
/// @name Cancelling HTTP Operations /// @name Cancelling HTTP Operations
@ -266,6 +289,16 @@
#pragma mark - #pragma mark -
@protocol AFHTTPClientOperation <NSObject>
+ (BOOL)canProcessRequest:(NSURLRequest *)request;
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;
+ (id)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure;
@end
#pragma mark -
/** /**
The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`. The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`.
*/ */
@ -322,3 +355,4 @@
*/ */
- (void)appendString:(NSString *)string; - (void)appendString:(NSString *)string;
@end @end

View file

@ -22,6 +22,9 @@
#import "AFHTTPClient.h" #import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h" #import "AFJSONRequestOperation.h"
#import "JSONKit.h"
#include <Availability.h>
static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF
static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";
@ -40,6 +43,8 @@ static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"
#pragma mark - #pragma mark -
static NSUInteger const kAFHTTPClientDefaultMaxConcurrentOperationCount = 4;
static NSString * AFBase64EncodedStringFromString(NSString *string) { static NSString * AFBase64EncodedStringFromString(NSString *string) {
NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string length]];
NSUInteger length = [data length]; NSUInteger length = [data length];
@ -69,14 +74,57 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) {
return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease]; return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease];
} }
static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { static NSString * AFURLEncodedStringFromString(NSString *string) {
static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|~ "; static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|~ ";
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease]; return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) autorelease];
}
static NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
NSMutableArray *mutableParameterComponents = [NSMutableArray array];
for (id key in [parameters allKeys]) {
NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromString([key description]), AFURLEncodedStringFromString([[parameters valueForKey:key] description])];
[mutableParameterComponents addObject:component];
}
return [mutableParameterComponents componentsJoinedByString:@"&"];
}
static NSString * AFJSONStringFromParameters(NSDictionary *parameters) {
NSString *JSONString = nil;
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
if ([NSJSONSerialization class]) {
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
if (!error) {
JSONString = [[[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding] autorelease];
}
} else {
JSONString = [parameters JSONString];
}
#else
JSONString = [parameters JSONString];
#endif
return JSONString;
}
static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) {
NSString *propertyListString = nil;
NSError *error = nil;
NSData *propertyListData = [NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if (!error) {
propertyListString = [[[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] autorelease];
}
return propertyListString;
} }
@interface AFHTTPClient () @interface AFHTTPClient ()
@property (readwrite, nonatomic, retain) NSURL *baseURL; @property (readwrite, nonatomic, retain) NSURL *baseURL;
@property (readwrite, nonatomic, retain) NSMutableArray *registeredHTTPOperationClassNames;
@property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders;
@property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue; @property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue;
@end @end
@ -84,6 +132,8 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
@implementation AFHTTPClient @implementation AFHTTPClient
@synthesize baseURL = _baseURL; @synthesize baseURL = _baseURL;
@synthesize stringEncoding = _stringEncoding; @synthesize stringEncoding = _stringEncoding;
@synthesize parameterEncoding = _parameterEncoding;
@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
@synthesize defaultHeaders = _defaultHeaders; @synthesize defaultHeaders = _defaultHeaders;
@synthesize operationQueue = _operationQueue; @synthesize operationQueue = _operationQueue;
@ -100,6 +150,9 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
self.baseURL = url; self.baseURL = url;
self.stringEncoding = NSUTF8StringEncoding; self.stringEncoding = NSUTF8StringEncoding;
self.parameterEncoding = AFJSONParameterEncoding;
self.registeredHTTPOperationClassNames = [NSMutableArray array];
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
@ -117,18 +170,35 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
// [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@, %@ %@, %@, Scale/%f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0)]]; // [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@, %@ %@, %@, Scale/%f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0)]];
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease]; self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
[self.operationQueue setMaxConcurrentOperationCount:2]; [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount];
return self; return self;
} }
- (void)dealloc { - (void)dealloc {
[_baseURL release]; [_baseURL release];
[_registeredHTTPOperationClassNames release];
[_defaultHeaders release]; [_defaultHeaders release];
[_operationQueue release]; [_operationQueue release];
[super dealloc]; [super dealloc];
} }
#pragma mark -
- (BOOL)registerHTTPOperationClass:(Class)operationClass {
if (![operationClass conformsToProtocol:@protocol(AFHTTPClientOperation)]) {
return NO;
}
NSString *className = NSStringFromClass(operationClass);
[self.registeredHTTPOperationClassNames removeObject:className];
[self.registeredHTTPOperationClassNames insertObject:className atIndex:0];
return YES;
}
#pragma mark -
- (NSString *)defaultValueForHeader:(NSString *)header { - (NSString *)defaultValueForHeader:(NSString *)header {
return [self.defaultHeaders valueForKey:header]; return [self.defaultHeaders valueForKey:header];
} }
@ -156,30 +226,33 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
path:(NSString *)path path:(NSString *)path
parameters:(NSDictionary *)parameters parameters:(NSDictionary *)parameters
{ {
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; NSURL *url = [self.baseURL URLByAppendingPathComponent:path];
NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; [request setHTTPMethod:method];
[request setAllHTTPHeaderFields:self.defaultHeaders];
if (parameters) { if (parameters) {
NSMutableArray *mutableParameterComponents = [NSMutableArray array];
for (id key in [parameters allKeys]) {
NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromStringWithEncoding([key description], self.stringEncoding), AFURLEncodedStringFromStringWithEncoding([[parameters valueForKey:key] description], self.stringEncoding)];
[mutableParameterComponents addObject:component];
}
NSString *queryString = [mutableParameterComponents componentsJoinedByString:@"&"];
if ([method isEqualToString:@"GET"]) { if ([method isEqualToString:@"GET"]) {
url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", queryString]]; url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParameters(parameters)]];
[request setURL:url];
} else { } else {
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
[headers setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forKey:@"Content-Type"]; switch (self.parameterEncoding) {
[request setHTTPBody:[queryString dataUsingEncoding:self.stringEncoding]]; case AFFormURLParameterEncoding:;
[request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[AFQueryStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
break;
case AFJSONParameterEncoding:;
[request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[AFJSONStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
break;
case AFPropertyListParameterEncoding:;
[request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[AFPropertyListStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]];
break;
}
} }
} }
[request setURL:url];
[request setHTTPMethod:method];
[request setAllHTTPHeaderFields:headers];
return request; return request;
} }
@ -224,20 +297,28 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
return request; return request;
} }
- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)urlRequest - (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{ {
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:urlRequest success:^(id JSON) { AFHTTPRequestOperation *operation = nil;
if (success) { NSString *className = nil;
success(JSON); NSEnumerator *enumerator = [self.registeredHTTPOperationClassNames reverseObjectEnumerator];
while (!operation && (className = [enumerator nextObject])) {
Class class = NSClassFromString(className);
if (class && [class canProcessRequest:urlRequest]) {
operation = [class HTTPRequestOperationWithRequest:urlRequest success:success failure:failure];
} }
} failure:^(NSHTTPURLResponse *response, NSError *error) {
if (failure) {
failure(response, error);
} }
}];
if (!operation) {
operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:urlRequest success:success failure:failure];
}
[self enqueueHTTPRequestOperation:operation];
}
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
[self.operationQueue addOperation:operation]; [self.operationQueue addOperation:operation];
} }
@ -257,7 +338,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{ {
NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters]; NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
[self enqueueHTTPOperationWithRequest:request success:success failure:failure]; [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure];
} }
- (void)postPath:(NSString *)path - (void)postPath:(NSString *)path
@ -266,7 +347,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{ {
NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters]; NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters];
[self enqueueHTTPOperationWithRequest:request success:success failure:failure]; [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure];
} }
- (void)putPath:(NSString *)path - (void)putPath:(NSString *)path
@ -275,7 +356,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{ {
NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters]; NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters];
[self enqueueHTTPOperationWithRequest:request success:success failure:failure]; [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure];
} }
- (void)deletePath:(NSString *)path - (void)deletePath:(NSString *)path
@ -284,7 +365,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{ {
NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters]; NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters];
[self enqueueHTTPOperationWithRequest:request success:success failure:failure]; [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure];
} }
@end @end

View file

@ -21,26 +21,11 @@
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
#import "AFHTTPClient.h"
/** /**
Indicates an error occured in AFNetworking. `AFHTTPRequestOperation` is an `NSOperation` subclass that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes.
@discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain.
*/
extern NSString * const AFNetworkingErrorDomain;
/**
Posted when an operation begins executing.
*/
extern NSString * const AFHTTPOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const AFHTTPOperationDidFinishNotification;
/**
`AFHTTPRequestOperation` is an `NSOperation` that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes.
# Subclassing Notes # Subclassing Notes
@ -50,7 +35,7 @@ extern NSString * const AFHTTPOperationDidFinishNotification;
## Methods to Subclass ## Methods to Subclass
Unless you need to override specific `NSURLConnection` delegate methods, you shouldn't need to subclass any methods. Instead, you should provide alternative constructor class methods, that are essentially wrappers around the callback from `AFHTTPRequestOperation`. //
### `NSURLConnection` Delegate Methods ### `NSURLConnection` Delegate Methods
@ -70,82 +55,43 @@ extern NSString * const AFHTTPOperationDidFinishNotification;
@see NSOperation @see NSOperation
@see NSURLConnection @see NSURLConnection
*/ */
@interface AFHTTPRequestOperation : NSOperation { @interface AFHTTPRequestOperation : AFURLConnectionOperation <AFHTTPClientOperation> {
@private @private
NSSet *_runLoopModes; NSIndexSet *_acceptableStatusCodes;
NSSet *_acceptableContentTypes;
NSURLConnection *_connection; NSError *_HTTPError;
NSURLRequest *_request;
NSHTTPURLResponse *_response;
NSError *_error;
NSData *_responseBody;
NSInteger _totalBytesRead;
NSMutableData *_dataAccumulator;
NSOutputStream *_outputStream;
} }
@property (nonatomic, retain) NSSet *runLoopModes;
@property (readonly, nonatomic, retain) NSURLRequest *request;
@property (readonly, nonatomic, retain) NSHTTPURLResponse *response; @property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
@property (readonly, nonatomic, retain) NSError *error;
@property (readonly, nonatomic, retain) NSData *responseBody; /**
@property (readonly) NSString *responseString; Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) used in operationWithRequest:success and operationWithRequest:success:failure.
By default, this is the range 200 to 299, inclusive.
*/
@property (nonatomic, retain) NSIndexSet *acceptableStatusCodes;
@property (nonatomic, retain) NSSet *acceptableContentTypes;
///--------------------------------------- ///---------------------------------------
/// @name Creating HTTP Request Operations /// @name Creating HTTP Request Operations
///--------------------------------------- ///---------------------------------------
/** //+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
Creates and returns an `AFHTTPRequestOperation` object and sets the specified completion callback. // success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success
// failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
@param urlRequest The request object to be loaded asynchronously during execution of the operation. ///-------------------------------
@param completion A block object to be executed when the HTTP request operation is finished. This block has no return value and takes four arguments: the request sent from the client, the response received from the server, the HTTP body received by the server during the execution of the request, and an error, which will have been set if an error occured while loading the request. /// @name Validating HTTP Response
///-------------------------------
@return A new HTTP request operation
*/
+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion;
/** /**
Creates and returns a streaming `AFHTTPRequestOperation` object and sets the specified input stream, output stream, and completion callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param inputStream The input stream object for reading data to be sent during the request. If set, the input stream is set as the `HTTPBodyStream` on the `NSMutableURLRequest`. If the request method is `GET`, it is changed to `POST`. This argument may be `nil`.
@param outputStream The output stream object for writing data received during the request. If set, data accumulated in `NSURLConnectionDelegate` methods will be sent to the output stream, and the NSData parameter in the completion block will be `nil`. This argument may be `nil`.
@param completion A block object to be executed when the HTTP request operation is finished. This block has no return value and takes four arguments: the request sent from the client, the response received from the server, the data received by the server during the execution of the request, and an error, which will have been set if an error occured while loading the request. This argument may be `nil`.
@see operationWithRequest:completion
@return A new streaming HTTP request operation
*/ */
+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest - (BOOL)hasAcceptableStatusCode;
inputStream:(NSInputStream *)inputStream
outputStream:(NSOutputStream *)outputStream
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion;
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/** /**
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 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.
@see setDownloadProgressBlock
*/ */
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block; - (BOOL)hasAcceptableContentType;
/**
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 read since the last time the upload 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.
@see setUploadProgressBlock
*/
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block;
@end @end

View file

@ -22,383 +22,80 @@
#import "AFHTTPRequestOperation.h" #import "AFHTTPRequestOperation.h"
static NSUInteger const kAFHTTPMinimumInitialDataCapacity = 1024;
static NSUInteger const kAFHTTPMaximumInitialDataCapacity = 1024 * 1024 * 8;
typedef enum {
AFHTTPOperationReadyState = 1,
AFHTTPOperationExecutingState = 2,
AFHTTPOperationFinishedState = 3,
AFHTTPOperationCancelledState = 4,
} AFHTTPOperationState;
NSString * const AFNetworkingErrorDomain = @"com.alamofire.networking.error";
NSString * const AFHTTPOperationDidStartNotification = @"com.alamofire.networking.http-operation.start";
NSString * const AFHTTPOperationDidFinishNotification = @"com.alamofire.networking.http-operation.finish";
typedef void (^AFHTTPRequestOperationProgressBlock)(NSInteger bytes, NSInteger totalBytes, NSInteger totalBytesExpected);
typedef void (^AFHTTPRequestOperationCompletionBlock)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error);
static inline NSString * AFKeyPathFromOperationState(AFHTTPOperationState state) {
switch (state) {
case AFHTTPOperationReadyState:
return @"isReady";
case AFHTTPOperationExecutingState:
return @"isExecuting";
case AFHTTPOperationFinishedState:
return @"isFinished";
default:
return @"state";
}
}
static inline BOOL AFHTTPOperationStateTransitionIsValid(AFHTTPOperationState from, AFHTTPOperationState to) {
switch (from) {
case AFHTTPOperationReadyState:
switch (to) {
case AFHTTPOperationExecutingState:
return YES;
default:
return NO;
}
case AFHTTPOperationExecutingState:
switch (to) {
case AFHTTPOperationReadyState:
return NO;
default:
return YES;
}
case AFHTTPOperationFinishedState:
return NO;
default:
return YES;
}
}
@interface AFHTTPRequestOperation () @interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, assign) AFHTTPOperationState state;
@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@property (readwrite, nonatomic, retain) NSURLConnection *connection;
@property (readwrite, nonatomic, retain) NSURLRequest *request;
@property (readwrite, nonatomic, retain) NSHTTPURLResponse *response;
@property (readwrite, nonatomic, retain) NSError *error; @property (readwrite, nonatomic, retain) NSError *error;
@property (readwrite, nonatomic, retain) NSData *responseBody;
@property (readwrite, nonatomic, assign) NSInteger totalBytesRead;
@property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator;
@property (readwrite, nonatomic, retain) NSOutputStream *outputStream;
@property (readwrite, nonatomic, copy) AFHTTPRequestOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) AFHTTPRequestOperationProgressBlock downloadProgress;
@property (readwrite, nonatomic, copy) AFHTTPRequestOperationCompletionBlock completion;
- (void)operationDidStart;
- (void)finish;
@end @end
@implementation AFHTTPRequestOperation @implementation AFHTTPRequestOperation
@synthesize state = _state; @synthesize acceptableStatusCodes = _acceptableStatusCodes;
@synthesize cancelled = _cancelled; @synthesize acceptableContentTypes = _acceptableContentTypes;
@synthesize connection = _connection; @synthesize error = _HTTPError;
@synthesize runLoopModes = _runLoopModes;
@synthesize request = _request;
@synthesize response = _response;
@synthesize error = _error;
@synthesize responseBody = _responseBody;
@synthesize totalBytesRead = _totalBytesRead;
@synthesize dataAccumulator = _dataAccumulator;
@synthesize outputStream = _outputStream;
@synthesize uploadProgress = _uploadProgress;
@synthesize downloadProgress = _downloadProgress;
@synthesize completion = _completion;
static NSThread *_networkRequestThread = nil; - (id)initWithRequest:(NSURLRequest *)request {
self = [super initWithRequest:request];
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
do {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] run];
[pool drain];
} while (YES);
}
+ (NSThread *)networkRequestThread {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
});
return _networkRequestThread;
}
+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion
{
AFHTTPRequestOperation *operation = [[[self alloc] init] autorelease];
operation.request = urlRequest;
operation.completion = completion;
return operation;
}
+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest
inputStream:(NSInputStream *)inputStream
outputStream:(NSOutputStream *)outputStream
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion
{
NSMutableURLRequest *mutableURLRequest = [[urlRequest mutableCopy] autorelease];
if (inputStream) {
[mutableURLRequest setHTTPBodyStream:inputStream];
if ([[mutableURLRequest HTTPMethod] isEqualToString:@"GET"]) {
[mutableURLRequest setHTTPMethod:@"POST"];
}
}
AFHTTPRequestOperation *operation = [self operationWithRequest:mutableURLRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, __unused NSData *data, NSError *error) {
if (completion) {
completion(request, response, error);
}
}];
operation.outputStream = outputStream;
return operation;
}
- (id)init {
self = [super init];
if (!self) { if (!self) {
return nil; return nil;
} }
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
self.state = AFHTTPOperationReadyState;
return self; return self;
} }
- (void)dealloc { - (void)dealloc {
[_runLoopModes release]; [_acceptableStatusCodes release];
[_acceptableContentTypes release];
[_request release]; [_HTTPError release];
[_response release];
[_responseBody release];
[_dataAccumulator release];
[_outputStream release]; _outputStream = nil;
[_connection release]; _connection = nil;
[_uploadProgress release];
[_downloadProgress release];
[_completion release];
[super dealloc]; [super dealloc];
} }
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block { - (NSHTTPURLResponse *)response {
self.uploadProgress = block; return (NSHTTPURLResponse *)[super response];
} }
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block { - (NSError *)error {
self.downloadProgress = block; if (self.response) {
if (![self hasAcceptableStatusCode]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), self.acceptableStatusCodes, [self.response statusCode]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
self.error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
} else if (![self hasAcceptableContentType]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), self.acceptableContentTypes, [self.response MIMEType]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
self.error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
}
}
return [super error];
} }
- (void)setState:(AFHTTPOperationState)state { - (BOOL)hasAcceptableStatusCode {
if (self.state == state) { return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]];
return;
}
if (!AFHTTPOperationStateTransitionIsValid(self.state, state)) {
return;
}
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
#if __IPHONE_OS_VERSION_MIN_REQUIRED
switch (state) {
case AFHTTPOperationExecutingState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidStartNotification object:self];
break;
case AFHTTPOperationFinishedState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidFinishNotification object:self];
break;
default:
break;
}
#endif
} }
- (void)setCancelled:(BOOL)cancelled { - (BOOL)hasAcceptableContentType {
[self willChangeValueForKey:@"isCancelled"]; return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]];
_cancelled = cancelled;
[self didChangeValueForKey:@"isCancelled"];
if ([self isCancelled]) {
self.state = AFHTTPOperationFinishedState;
}
} }
- (NSString *)responseString { #pragma mark - AFHTTPClientOperation
if (!self.response || !self.responseBody) {
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return NO;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
return request;
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return nil; return nil;
}
NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName));
return [[[NSString alloc] initWithData:self.responseBody encoding:textEncoding] autorelease];
}
#pragma mark - NSOperation
- (BOOL)isReady {
return self.state == AFHTTPOperationReadyState;
}
- (BOOL)isExecuting {
return self.state == AFHTTPOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == AFHTTPOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
if (![self isReady]) {
return;
}
self.state = AFHTTPOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]];
}
- (void)operationDidStart {
self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease];
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];
}
- (void)cancel {
if ([self isFinished]) {
return;
}
[super cancel];
self.cancelled = YES;
[self.connection cancel];
}
- (void)finish {
self.state = AFHTTPOperationFinishedState;
if ([self isCancelled]) {
return;
}
if (self.completion) {
self.completion(self.request, self.response, self.responseBody, self.error);
}
}
#pragma mark - NSURLConnection
- (void)connection:(NSURLConnection *)__unused connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = (NSHTTPURLResponse *)response;
if (self.outputStream) {
[self.outputStream open];
} else {
NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), kAFHTTPMinimumInitialDataCapacity);
NSUInteger capacity = MIN(maxCapacity, kAFHTTPMaximumInitialDataCapacity);
self.dataAccumulator = [NSMutableData dataWithCapacity:capacity];
}
}
- (void)connection:(NSURLConnection *)__unused connection
didReceiveData:(NSData *)data
{
self.totalBytesRead += [data length];
if (self.outputStream) {
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = [data bytes];
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
}
} else {
[self.dataAccumulator appendData:data];
}
if (self.downloadProgress) {
self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength);
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection {
if (self.outputStream) {
[self.outputStream close];
} else {
self.responseBody = [NSData dataWithData:self.dataAccumulator];
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (void)connection:(NSURLConnection *)__unused connection
didFailWithError:(NSError *)error
{
self.error = error;
if (self.outputStream) {
[self.outputStream close];
} else {
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (void)connection:(NSURLConnection *)__unused connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.uploadProgress) {
self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
} }
@end @end

View file

@ -21,17 +21,21 @@
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "AFHTTPRequestOperation.h" #import "AFHTTPRequestOperation.h"
#import <Availability.h>
/** /**
`AFImageRequestOperation` is an `NSOperation` that wraps the callback from `AFHTTPRequestOperation` to create an image from the response body, and optionally cache the image to memory. `AFImageRequestOperation` is an `NSOperation` that wraps the callback from `AFHTTPRequestOperation` to create an image from the response body, and optionally cache the image to memory.
@see NSOperation @see NSOperation
@see AFHTTPRequestOperation @see AFHTTPRequestOperation
*/ */
@interface AFImageRequestOperation : AFHTTPRequestOperation @interface AFImageRequestOperation : AFHTTPRequestOperation {
@private
UIImage *_responseImage;
}
@property (readonly, nonatomic, retain) UIImage *responseImage;
/** /**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@ -41,11 +45,8 @@
@return A new image request operation @return A new image request operation
*/ */
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success; success:(void (^)(UIImage *image))success;
#endif
/** /**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@ -58,13 +59,10 @@
@return A new image request operation @return A new image request operation
*/ */
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
cacheName:(NSString *)cacheNameOrNil cacheName:(NSString *)cacheNameOrNil
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#endif
@end @end

View file

@ -26,67 +26,127 @@
static dispatch_queue_t af_image_request_operation_processing_queue; static dispatch_queue_t af_image_request_operation_processing_queue;
static dispatch_queue_t image_request_operation_processing_queue() { static dispatch_queue_t image_request_operation_processing_queue() {
if (af_image_request_operation_processing_queue == NULL) { if (af_image_request_operation_processing_queue == NULL) {
af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.image-request.processing", 0); af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0);
} }
return af_image_request_operation_processing_queue; return af_image_request_operation_processing_queue;
} }
@interface AFImageRequestOperation ()
@property (readwrite, nonatomic, retain) UIImage *responseImage;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFImageRequestOperation @implementation AFImageRequestOperation
@synthesize responseImage = _responseImage;
#if __IPHONE_OS_VERSION_MIN_REQUIRED + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success success:(void (^)(UIImage *image))success
{ {
return [self operationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
if (success) { if (success) {
success(image); success(image);
} }
} failure:nil]; } failure:nil];
} }
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
cacheName:(NSString *)cacheNameOrNil cacheName:(NSString *)cacheNameOrNil
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{ {
return (AFImageRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { AFImageRequestOperation *operation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
dispatch_async(image_request_operation_processing_queue(), ^(void) { dispatch_async(image_request_operation_processing_queue(), ^(void) {
if (error) { if (operation.error) {
if (failure) { if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) { dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(request, response, error); failure(operation.request, operation.response, operation.error);
}); });
} }
} else { } else {
UIImage *image = nil; UIImage *image = operation.responseImage;
if ([[UIScreen mainScreen] scale] == 2.0) {
CGImageRef imageRef = [[UIImage imageWithData:data] CGImage];
image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp];
} else {
image = [UIImage imageWithData:data];
}
if (imageProcessingBlock) { if (imageProcessingBlock) {
image = imageProcessingBlock(image); image = imageProcessingBlock(image);
} }
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (success) { if (success) {
success(request, response, image); dispatch_async(dispatch_get_main_queue(), ^(void) {
} success(operation.request, operation.response, image);
}); });
}
if ([request cachePolicy] != NSURLCacheStorageNotAllowed) { if ([operation.request cachePolicy] != NSURLCacheStorageNotAllowed) {
[[AFImageCache sharedImageCache] cacheImage:image forURL:[request URL] cacheName:cacheNameOrNil]; [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil];
} }
} }
}); });
};
return operation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseImage release];
[super dealloc];
}
- (UIImage *)responseImage {
if (!_responseImage && [self isFinished]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
CGImageRef imageRef = [[UIImage imageWithData:self.responseData] CGImage];
self.responseImage = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp];
} else {
self.responseImage = [UIImage imageWithData:self.responseData];
}
}
return _responseImage;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) {
success(image);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}]; }];
} }
#endif
@end @end

View file

@ -29,44 +29,18 @@
@see NSOperation @see NSOperation
@see AFHTTPRequestOperation @see AFHTTPRequestOperation
*/ */
@interface AFJSONRequestOperation : AFHTTPRequestOperation @interface AFJSONRequestOperation : AFHTTPRequestOperation {
@private
id _responseJSON;
NSError *_JSONError;
}
@property (readonly, nonatomic, retain) id responseJSON;
///--------------------------------------- ///---------------------------------------
/// @name Creating JSON Request Operations /// @name Creating JSON Request Operations
///--------------------------------------- ///---------------------------------------
/**
Creates and returns an `AFJSONRequestOperation` 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 JSON request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is the JSON object created from the response data of request, or nil if there was an error.
@see defaultAcceptableStatusCodes
@see defaultAcceptableContentTypes
@see operationWithRequest:success:failure:
@return A new JSON request operation
*/
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success;
/**
Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the JSON request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is the JSON object created from the response data of request.
@param failure A block object to be executed when the JSON request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a two arguments: the response from the server, and the error describing the network or parsing error that occurred.
@see defaultAcceptableStatusCodes
@see defaultAcceptableContentTypes
@see operationWithRequest:success:
@return A new JSON request operation
*/
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure;
/** /**
Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks, as well as the status codes and content types that are acceptable for a successful request. Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks, as well as the status codes and content types that are acceptable for a successful request.
@ -78,29 +52,7 @@
@return A new JSON request operation @return A new JSON request operation
*/ */
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes
acceptableContentTypes:(NSSet *)acceptableContentTypes
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
///----------------------------------
/// @name Getting Default HTTP Values
///----------------------------------
/**
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) used in operationWithRequest:success and operationWithRequest:success:failure.
By default, this is the range 200 to 299, inclusive.
*/
+ (NSIndexSet *)defaultAcceptableStatusCodes;
/**
Returns an `NSSet` object containing the acceptable HTTP content type (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17) used in operationWithRequest:success and operationWithRequest:success:failure.
By default, this contains `application/json`, `application/x-javascript`, `text/javascript`, `text/x-javascript`, `text/x-json`, `text/json`, and `text/plain`
*/
+ (NSSet *)defaultAcceptableContentTypes;
@end @end

View file

@ -28,108 +28,124 @@
static dispatch_queue_t af_json_request_operation_processing_queue; static dispatch_queue_t af_json_request_operation_processing_queue;
static dispatch_queue_t json_request_operation_processing_queue() { static dispatch_queue_t json_request_operation_processing_queue() {
if (af_json_request_operation_processing_queue == NULL) { if (af_json_request_operation_processing_queue == NULL) {
af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.json-request.processing", 0); af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0);
} }
return af_json_request_operation_processing_queue; return af_json_request_operation_processing_queue;
} }
@interface AFJSONRequestOperation ()
@property (readwrite, nonatomic, retain) id responseJSON;
@property (readwrite, nonatomic, retain) NSError *error;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFJSONRequestOperation @implementation AFJSONRequestOperation
@synthesize responseJSON = _responseJSON;
@synthesize error = _JSONError;
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success
{
return [self operationWithRequest:urlRequest success:success failure:nil];
}
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self operationWithRequest:urlRequest acceptableStatusCodes:[self defaultAcceptableStatusCodes] acceptableContentTypes:[self defaultAcceptableContentTypes] success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) {
if (success) {
success(JSON);
}
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
if (failure) {
failure(response, error);
}
}];
}
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes
acceptableContentTypes:(NSSet *)acceptableContentTypes
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{ {
return (AFJSONRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { AFJSONRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
if (!error) { operation.completionBlock = ^ {
if (acceptableStatusCodes && ![acceptableStatusCodes containsIndex:[response statusCode]]) { if ([operation isCancelled]) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; return;
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), acceptableStatusCodes, [response statusCode]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey];
error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
} }
if (acceptableContentTypes && ![acceptableContentTypes containsObject:[response MIMEType]]) { if (operation.error) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), acceptableContentTypes, [response MIMEType]] forKey:NSLocalizedDescriptionKey];
[userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey];
error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease];
}
}
if (error) {
if (failure) { if (failure) {
dispatch_async(dispatch_get_main_queue(), ^{ dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(request, response, error); failure(operation.request, operation.response, operation.error);
});
}
} else if ([data length] == 0) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
success(request, response, nil);
}); });
} }
} else { } else {
dispatch_async(json_request_operation_processing_queue(), ^(void) { dispatch_async(json_request_operation_processing_queue(), ^(void) {
id JSON = nil; NSError *error = nil;
NSError *JSONError = nil; id JSON = operation.responseJSON;
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 operation.error = error;
if ([NSJSONSerialization class]) {
JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError];
} else {
JSON = [[JSONDecoder decoder] objectWithData:data error:&JSONError];
}
#else
JSON = [[JSONDecoder decoder] objectWithData:data error:&JSONError];
#endif
dispatch_async(dispatch_get_main_queue(), ^(void) { dispatch_async(dispatch_get_main_queue(), ^(void) {
if (JSONError) { if (operation.error) {
if (failure) { if (failure) {
failure(request, response, JSONError); failure(operation.request, operation.response, operation.error);
} }
} else { } else {
if (success) { if (success) {
success(request, response, JSON); success(operation.request, operation.response, JSON);
} }
} }
}); });
}); });
} }
}]; };
}
+ (NSIndexSet *)defaultAcceptableStatusCodes { return operation;
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
} }
+ (NSSet *)defaultAcceptableContentTypes { + (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil];
} }
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"json", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseJSON release];
[_JSONError release];
[super dealloc];
}
- (id)responseJSON {
if (!_responseJSON && [self isFinished]) {
NSError *error = nil;
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
if ([NSJSONSerialization class]) {
self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error];
} else {
self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error];
}
#else
self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error];
#endif
self.error = error;
}
return _responseJSON;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self JSONRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) {
success(JSON);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
@end @end

View file

@ -31,6 +31,7 @@
@private @private
NSInteger _activityCount; NSInteger _activityCount;
BOOL _enabled; BOOL _enabled;
NSTimer *_activityIndicatorVisibilityTimer;
} }
/** /**

View file

@ -24,14 +24,21 @@
#import "AFHTTPRequestOperation.h" #import "AFHTTPRequestOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25;
@interface AFNetworkActivityIndicatorManager () @interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount; @property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, retain) NSTimer *activityIndicatorVisibilityTimer;
@property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateNetworkActivityIndicatorVisibility;
@end @end
@implementation AFNetworkActivityIndicatorManager @implementation AFNetworkActivityIndicatorManager
@synthesize activityCount = _activityCount; @synthesize activityCount = _activityCount;
@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer;
@synthesize enabled = _enabled; @synthesize enabled = _enabled;
@dynamic networkActivityIndicatorVisible;
+ (AFNetworkActivityIndicatorManager *)sharedManager { + (AFNetworkActivityIndicatorManager *)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil; static AFNetworkActivityIndicatorManager *_sharedManager = nil;
@ -49,8 +56,8 @@
return nil; return nil;
} }
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFHTTPOperationDidStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFHTTPOperationDidFinishNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil];
return self; return self;
} }
@ -58,6 +65,9 @@
- (void)dealloc { - (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self]; [[NSNotificationCenter defaultCenter] removeObserver:self];
[_activityIndicatorVisibilityTimer invalidate];
[_activityIndicatorVisibilityTimer release]; _activityIndicatorVisibilityTimer = nil;
[super dealloc]; [super dealloc];
} }
@ -67,8 +77,23 @@
[self didChangeValueForKey:@"activityCount"]; [self didChangeValueForKey:@"activityCount"];
if (self.enabled) { if (self.enabled) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:self.activityCount > 0]; // Delay hiding of activity indicator for a short interval, to avoid flickering
if (![self isNetworkActivityIndicatorVisible]) {
[self.activityIndicatorVisibilityTimer invalidate];
self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes];
} else {
[self updateNetworkActivityIndicatorVisibility];
} }
}
}
- (BOOL)isNetworkActivityIndicatorVisible {
return self.activityCount > 0;
}
- (void)updateNetworkActivityIndicatorVisibility {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]];
} }
- (void)incrementActivityCount { - (void)incrementActivityCount {
@ -84,4 +109,3 @@
} }
@end @end
#endif

View file

@ -0,0 +1,46 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation {
@private
id _responsePropertyList;
NSPropertyListFormat _propertyListFormat;
NSPropertyListReadOptions _propertyListReadOptions;
NSError *_propertyListError;
}
@property (readonly, nonatomic, retain) id responsePropertyList;
@property (readonly, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
/**
*/
+ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
@end

View file

@ -0,0 +1,144 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFPropertyListRequestOperation.h"
static dispatch_queue_t af_property_list_request_operation_processing_queue;
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;
}
@interface AFPropertyListRequestOperation ()
@property (readwrite, nonatomic, retain) id responsePropertyList;
@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (readwrite, nonatomic, retain) NSError *error;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFPropertyListRequestOperation
@synthesize responsePropertyList = _responsePropertyList;
@synthesize propertyListReadOptions = _propertyListReadOptions;
@synthesize propertyListFormat = _propertyListFormat;
@synthesize error = _propertyListError;
+ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFPropertyListRequestOperation *operation = [[[self alloc] initWithRequest:request] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (operation.error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
id propertyList = operation.responsePropertyList;
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (operation.error) {
if (failure) {
failure(operation.request, operation.response, operation.error);
}
} else {
if (success) {
success(operation.request, operation.response, propertyList);
}
}
});
});
}
};
return operation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"plist", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil];
self.propertyListReadOptions = NSPropertyListImmutable;
self.propertyListFormat = NSPropertyListXMLFormat_v1_0;
return self;
}
- (void)dealloc {
[_responsePropertyList release];
[_propertyListError release];
[super dealloc];
}
- (id)responsePropertyList {
if (!_responsePropertyList && [self isFinished]) {
NSPropertyListFormat format;
NSError *error = nil;
self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
self.propertyListFormat = format;
self.error = error;
}
return _responsePropertyList;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self propertyListRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id propertyList) {
success(propertyList);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
@end

View file

@ -0,0 +1,97 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
/**
Indicates an error occured in AFNetworking.
@discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain.
*/
extern NSString * const AFNetworkingErrorDomain;
/**
Posted when an operation begins executing.
*/
extern NSString * const AFNetworkingOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const AFNetworkingOperationDidFinishNotification;
@interface AFURLConnectionOperation : NSOperation {
@private
NSSet *_runLoopModes;
NSURLConnection *_connection;
NSURLRequest *_request;
NSHTTPURLResponse *_response;
NSError *_error;
NSData *_responseData;
NSInteger _totalBytesRead;
NSMutableData *_dataAccumulator;
NSOutputStream *_outputStream;
}
@property (nonatomic, retain) NSSet *runLoopModes;
@property (readonly, nonatomic, retain) NSURLRequest *request;
@property (readonly, nonatomic, retain) NSURLResponse *response;
@property (readonly, nonatomic, retain) NSError *error;
@property (readonly, nonatomic, retain) NSData *responseData;
@property (readonly, nonatomic, copy) NSString *responseString;
@property (nonatomic, retain) NSInputStream *inputStream;
@property (nonatomic, retain) NSOutputStream *outputStream;
/**
@discussion This is the designated initializer.
*/
- (id)initWithRequest:(NSURLRequest *)urlRequest;
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
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 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.
@see setDownloadProgressBlock
*/
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block;
/**
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 read since the last time the upload 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.
@see setUploadProgressBlock
*/
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block;
@end

View file

@ -0,0 +1,389 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFURLConnectionOperation.h"
static NSUInteger const kAFHTTPMinimumInitialDataCapacity = 1024;
static NSUInteger const kAFHTTPMaximumInitialDataCapacity = 1024 * 1024 * 8;
typedef enum {
AFHTTPOperationReadyState = 1,
AFHTTPOperationExecutingState = 2,
AFHTTPOperationFinishedState = 3,
} AFOperationState;
NSString * const AFNetworkingErrorDomain = @"com.alamofire.networking.error";
NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
typedef void (^AFURLConnectionOperationProgressBlock)(NSInteger bytes, NSInteger totalBytes, NSInteger totalBytesExpected);
static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
switch (state) {
case AFHTTPOperationReadyState:
return @"isReady";
case AFHTTPOperationExecutingState:
return @"isExecuting";
case AFHTTPOperationFinishedState:
return @"isFinished";
default:
return @"state";
}
}
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, assign) AFOperationState state;
@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@property (readwrite, nonatomic, retain) NSURLConnection *connection;
@property (readwrite, nonatomic, retain) NSURLRequest *request;
@property (readwrite, nonatomic, retain) NSURLResponse *response;
@property (readwrite, nonatomic, retain) NSError *error;
@property (readwrite, nonatomic, retain) NSData *responseData;
@property (readwrite, nonatomic, copy) NSString *responseString;
@property (readwrite, nonatomic, assign) NSInteger totalBytesRead;
@property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
- (BOOL)shouldTransitionToState:(AFOperationState)state;
- (void)operationDidStart;
- (void)finish;
@end
@implementation AFURLConnectionOperation
@synthesize state = _state;
@synthesize cancelled = _cancelled;
@synthesize connection = _connection;
@synthesize runLoopModes = _runLoopModes;
@synthesize request = _request;
@synthesize response = _response;
@synthesize error = _error;
@synthesize responseData = _responseData;
@synthesize responseString = _responseString;
@synthesize totalBytesRead = _totalBytesRead;
@synthesize dataAccumulator = _dataAccumulator;
@dynamic inputStream;
@synthesize outputStream = _outputStream;
@synthesize uploadProgress = _uploadProgress;
@synthesize downloadProgress = _downloadProgress;
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
do {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] run];
[pool drain];
} while (YES);
}
+ (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;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super init];
if (!self) {
return nil;
}
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.request = urlRequest;
self.state = AFHTTPOperationReadyState;
return self;
}
- (void)dealloc {
[_runLoopModes release];
[_request release];
[_response release];
[_error release];
[_responseData release];
[_responseString release];
[_dataAccumulator release];
[_outputStream release]; _outputStream = nil;
[_connection release]; _connection = nil;
[_uploadProgress release];
[_downloadProgress release];
[super dealloc];
}
- (void)setCompletionBlock:(void (^)(void))block {
if (!block) {
[super setCompletionBlock:nil];
}
__block id _blockSelf = self;
[super setCompletionBlock:^ {
block();
dispatch_async(dispatch_get_main_queue(), ^(void) {
[_blockSelf setCompletionBlock:nil];
});
}];
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
if (inputStream) {
NSMutableURLRequest *mutableRequest = [[self.request mutableCopy] autorelease];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
}
}
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setState:(AFOperationState)state {
if (![self shouldTransitionToState:state]) {
return;
}
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
switch (state) {
case AFHTTPOperationExecutingState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
break;
case AFHTTPOperationFinishedState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
break;
default:
break;
}
}
- (BOOL)shouldTransitionToState:(AFOperationState)state {
switch (self.state) {
case AFHTTPOperationReadyState:
switch (state) {
case AFHTTPOperationExecutingState:
return YES;
default:
return NO;
}
case AFHTTPOperationExecutingState:
switch (state) {
case AFHTTPOperationFinishedState:
return YES;
default:
return NO;
}
case AFHTTPOperationFinishedState:
return NO;
default:
return YES;
}
}
- (void)setCancelled:(BOOL)cancelled {
[self willChangeValueForKey:@"isCancelled"];
_cancelled = cancelled;
[self didChangeValueForKey:@"isCancelled"];
if ([self isCancelled]) {
self.state = AFHTTPOperationFinishedState;
}
}
- (NSString *)responseString {
if (!_responseString && self.response && self.responseData) {
NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName));
self.responseString = [[[NSString alloc] initWithData:self.responseData encoding:textEncoding] autorelease];
}
return _responseString;
}
#pragma mark - NSOperation
- (BOOL)isReady {
return self.state == AFHTTPOperationReadyState;
}
- (BOOL)isExecuting {
return self.state == AFHTTPOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == AFHTTPOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
if (![self isReady]) {
return;
}
self.state = AFHTTPOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]];
}
- (void)operationDidStart {
if ([self isCancelled]) {
[self finish];
return;
}
self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease];
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];
}
- (void)finish {
self.state = AFHTTPOperationFinishedState;
}
- (void)cancel {
if ([self isFinished]) {
return;
}
[super cancel];
self.cancelled = YES;
[self.connection cancel];
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)__unused connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.uploadProgress) {
self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
- (void)connection:(NSURLConnection *)__unused connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = (NSHTTPURLResponse *)response;
if (self.outputStream) {
[self.outputStream open];
} else {
NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), kAFHTTPMinimumInitialDataCapacity);
NSUInteger capacity = MIN(maxCapacity, kAFHTTPMaximumInitialDataCapacity);
self.dataAccumulator = [NSMutableData dataWithCapacity:capacity];
}
}
- (void)connection:(NSURLConnection *)__unused connection
didReceiveData:(NSData *)data
{
self.totalBytesRead += [data length];
if (self.outputStream) {
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = [data bytes];
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
}
} else {
[self.dataAccumulator appendData:data];
}
if (self.downloadProgress) {
self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength);
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection {
if (self.outputStream) {
[self.outputStream close];
} else {
self.responseData = [NSData dataWithData:self.dataAccumulator];
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (void)connection:(NSURLConnection *)__unused connection
didFailWithError:(NSError *)error
{
self.error = error;
if (self.outputStream) {
[self.outputStream close];
} else {
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
@end

View file

@ -0,0 +1,37 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
@interface AFXMLRequestOperation : AFHTTPRequestOperation {
@private
NSXMLParser *_responseXMLParser;
}
@property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser;
+ (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
@end

View file

@ -0,0 +1,123 @@
// 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
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFXMLRequestOperation.h"
#include <Availability.h>
@interface AFXMLRequestOperation ()
@property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFXMLRequestOperation
@synthesize responseXMLParser = _responseXMLParser;
+ (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFXMLRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (operation.error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
NSXMLParser *XMLParser = operation.responseXMLParser;
if (success) {
success(operation.request, operation.response, XMLParser);
}
}
};
return operation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"xml", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
_responseXMLParser.delegate = nil;
[_responseXMLParser release];
[super dealloc];
}
- (NSXMLParser *)responseXMLParser {
if (!_responseXMLParser && [self isFinished]) {
self.responseXMLParser = [[[NSXMLParser alloc] initWithData:self.responseData] autorelease];
}
return _responseXMLParser;
}
#pragma mark - NSOperation
- (void)cancel {
[super cancel];
self.responseXMLParser.delegate = nil;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self XMLParserRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSXMLParser *XMLParser) {
success(XMLParser);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
@end

View file

@ -29,7 +29,7 @@
#import "AFImageCache.h" #import "AFImageCache.h"
static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOperation"; static char kAFImageRequestOperationObjectKey;
@interface UIImageView (_AFNetworking) @interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, retain, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; @property (readwrite, nonatomic, retain, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation;
@ -44,11 +44,11 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
@implementation UIImageView (AFNetworking) @implementation UIImageView (AFNetworking)
- (AFHTTPRequestOperation *)af_imageRequestOperation { - (AFHTTPRequestOperation *)af_imageRequestOperation {
return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, kAFImageRequestOperationObjectKey); return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey);
} }
- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { - (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation {
objc_setAssociatedObject(self, kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
} }
+ (NSOperationQueue *)af_sharedImageRequestOperationQueue { + (NSOperationQueue *)af_sharedImageRequestOperationQueue {
@ -80,10 +80,10 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response,UIImage *image))success success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{ {
if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:self.af_imageRequestOperation.request.URL])) { if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]])) {
return; return;
} else { } else {
[self cancelImageRequestOperation]; [self cancelImageRequestOperation];
@ -99,9 +99,8 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
} else { } else {
self.image = placeholderImage; self.image = placeholderImage;
self.af_imageRequestOperation = [AFImageRequestOperation operationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) { if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) {
dispatch_async(dispatch_get_main_queue(), ^{
if (success) { if (success) {
success(request, response, image); success(request, response, image);
} }
@ -111,16 +110,13 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
} else { } else {
self.image = placeholderImage; self.image = placeholderImage;
} }
});
} }
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
self.af_imageRequestOperation = nil; self.af_imageRequestOperation = nil;
dispatch_async(dispatch_get_main_queue(), ^{
if (failure) { if (failure) {
failure(request, response, error); failure(request, response, error);
} }
});
}]; }];
[[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation];

View file

@ -7,6 +7,7 @@
objects = { objects = {
/* Begin PBXBuildFile section */ /* Begin PBXBuildFile section */
F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */; };
F874B5D913E0AA6500B28E3E /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */; }; F874B5D913E0AA6500B28E3E /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */; };
F874B5DA13E0AA6500B28E3E /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CA13E0AA6500B28E3E /* AFImageCache.m */; }; F874B5DA13E0AA6500B28E3E /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CA13E0AA6500B28E3E /* AFImageCache.m */; };
F874B5DB13E0AA6500B28E3E /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */; }; F874B5DB13E0AA6500B28E3E /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */; };
@ -29,10 +30,14 @@
F8E469671395739D00DB05C8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469661395739D00DB05C8 /* Foundation.framework */; }; F8E469671395739D00DB05C8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469661395739D00DB05C8 /* Foundation.framework */; };
F8E469691395739D00DB05C8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469681395739D00DB05C8 /* CoreGraphics.framework */; }; F8E469691395739D00DB05C8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469681395739D00DB05C8 /* CoreGraphics.framework */; };
F8E469DF13957DD500DB05C8 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469DE13957DD500DB05C8 /* CoreLocation.framework */; }; F8E469DF13957DD500DB05C8 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469DE13957DD500DB05C8 /* CoreLocation.framework */; };
F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */; };
F8F4B17F143E07030064C9E6 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */; };
F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FBFA97142AA238001409DB /* AFHTTPClient.m */; }; F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FBFA97142AA238001409DB /* AFHTTPClient.m */; };
/* End PBXBuildFile section */ /* End PBXBuildFile section */
/* Begin PBXFileReference section */ /* Begin PBXFileReference section */
F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = ../AFNetworking/AFURLConnectionOperation.h; sourceTree = "<group>"; };
F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = "<group>"; };
F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; }; F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; };
F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = "<group>"; }; F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = "<group>"; };
F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; }; F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; };
@ -71,6 +76,10 @@
F8E469DE13957DD500DB05C8 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; }; F8E469DE13957DD500DB05C8 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; };
F8E469E013957DF100DB05C8 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; F8E469E013957DF100DB05C8 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
F8E469E213957DF700DB05C8 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; F8E469E213957DF700DB05C8 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; };
F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFPropertyListRequestOperation.h; path = ../AFNetworking/AFPropertyListRequestOperation.h; sourceTree = "<group>"; };
F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFXMLRequestOperation.h; path = ../AFNetworking/AFXMLRequestOperation.h; sourceTree = "<group>"; };
F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFXMLRequestOperation.m; path = ../AFNetworking/AFXMLRequestOperation.m; sourceTree = "<group>"; };
F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = "<group>"; }; F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = "<group>"; };
F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = "<group>"; }; F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = "<group>"; };
/* End PBXFileReference section */ /* End PBXFileReference section */
@ -221,10 +230,16 @@
F8E469941395744600DB05C8 /* AFNetworking */ = { F8E469941395744600DB05C8 /* AFNetworking */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */,
F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */,
F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */, F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */,
F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */,
F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */,
F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */,
F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */,
F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */,
F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */,
F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */,
F8FBFA96142AA237001409DB /* AFHTTPClient.h */, F8FBFA96142AA237001409DB /* AFHTTPClient.h */,
F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F8FBFA97142AA238001409DB /* AFHTTPClient.m */,
F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */,
@ -335,6 +350,9 @@
F874B5DD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m in Sources */, F874B5DD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m in Sources */,
F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */, F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */,
F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */, F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */,
F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */,
F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */,
F8F4B17F143E07030064C9E6 /* AFXMLRequestOperation.m in Sources */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };

View file

@ -22,6 +22,8 @@
#import "AFGowallaAPIClient.h" #import "AFGowallaAPIClient.h"
#import "AFJSONRequestOperation.h"
// Replace this with your own API Key, available at http://api.gowalla.com/api/keys/ // Replace this with your own API Key, available at http://api.gowalla.com/api/keys/
NSString * const kAFGowallaClientID = @"e7ccb7d3d2414eb2af4663fc91eb2793"; NSString * const kAFGowallaClientID = @"e7ccb7d3d2414eb2af4663fc91eb2793";
@ -54,6 +56,8 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/";
// X-UDID HTTP Header // X-UDID HTTP Header
[self setDefaultHeader:@"X-UDID" value:[[UIDevice currentDevice] uniqueIdentifier]]; [self setDefaultHeader:@"X-UDID" value:[[UIDevice currentDevice] uniqueIdentifier]];
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
return self; return self;
} }

View file

@ -43,6 +43,7 @@
self.detailTextLabel.backgroundColor = self.backgroundColor; self.detailTextLabel.backgroundColor = self.backgroundColor;
self.imageView.backgroundColor = self.backgroundColor; self.imageView.backgroundColor = self.backgroundColor;
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.selectionStyle = UITableViewCellSelectionStyleGray; self.selectionStyle = UITableViewCellSelectionStyleGray;
@ -73,4 +74,24 @@
self.detailTextLabel.text = nil; self.detailTextLabel.text = nil;
} }
#pragma mark - UIView
- (void)layoutSubviews {
[super layoutSubviews];
CGRect imageViewFrame = self.imageView.frame;
CGRect textLabelFrame = self.textLabel.frame;
CGRect detailTextLabelFrame = self.detailTextLabel.frame;
imageViewFrame.origin = CGPointMake(10.0f, 10.0f);
imageViewFrame.size = CGSizeMake(50.0f, 50.0f);
textLabelFrame.origin.x = imageViewFrame.size.width + 25.0f;
detailTextLabelFrame.origin.x = textLabelFrame.origin.x;
textLabelFrame.size.width = 240.0f;
detailTextLabelFrame.size.width = textLabelFrame.size.width;
self.textLabel.frame = textLabelFrame;
self.detailTextLabel.frame = detailTextLabelFrame;
self.imageView.frame = imageViewFrame;
}
@end @end