Initial working implementation of new candidate class structure

This commit is contained in:
Mattt Thompson 2011-10-04 00:13:12 -05:00
parent 97d4d179df
commit 561df45eb7
12 changed files with 656 additions and 583 deletions

View file

@ -228,11 +228,11 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
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) { AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) {
if (success) { if (success) {
success(JSON); success(JSON);
} }
} failure:^(NSHTTPURLResponse *response, NSError *error) { } failure:^(__unused NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
if (failure) { if (failure) {
failure(response, error); failure(response, error);
} }

View file

@ -21,26 +21,10 @@
// THE SOFTWARE. // THE SOFTWARE.
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.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 +34,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 +54,42 @@ extern NSString * const AFHTTPOperationDidFinishNotification;
@see NSOperation @see NSOperation
@see NSURLConnection @see NSURLConnection
*/ */
@interface AFHTTPRequestOperation : NSOperation { @interface AFHTTPRequestOperation : AFURLConnectionOperation {
@private @private
NSSet *_runLoopModes; NSIndexSet *_acceptableStatusCodes;
NSSet *_acceptableContentTypes;
NSURLConnection *_connection;
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,381 +22,86 @@
#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; @dynamic error;
@synthesize cancelled = _cancelled; @dynamic response;
@synthesize connection = _connection; @synthesize acceptableStatusCodes = _acceptableStatusCodes;
@synthesize runLoopModes = _runLoopModes; @synthesize acceptableContentTypes = _acceptableContentTypes;
@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; + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success
+ (void)networkRequestThreadEntryPoint:(id)__unused object { failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
do { {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
[[NSRunLoop currentRunLoop] run]; operation.completionBlock = ^ {
[pool drain]; if (operation.error) {
} while (YES); if (failure) {
} dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
+ (NSThread *)networkRequestThread {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
}); });
}
return _networkRequestThread; } else {
} if (success) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest success(operation.request, operation.response, operation.responseBody);
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; return operation;
} }
+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest - (id)initWithRequest:(NSURLRequest *)request {
inputStream:(NSInputStream *)inputStream self = [super initWithRequest:request];
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];
[_request 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 && ![super error]) {
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];
switch (state) {
case AFHTTPOperationExecutingState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidStartNotification object:self];
break;
case AFHTTPOperationFinishedState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidFinishNotification object:self];
break;
default:
break;
}
} }
- (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 {
if (!self.response || !self.responseBody) {
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

@ -40,7 +40,7 @@
@return A new image request operation @return A new image request operation
*/ */
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success; success:(void (^)(UIImage *image))success;
/** /**
@ -54,7 +54,7 @@
@return A new image request operation @return A new image request operation
*/ */
+ (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

View file

@ -26,7 +26,7 @@
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;
@ -34,37 +34,39 @@ static dispatch_queue_t image_request_operation_processing_queue() {
@implementation AFImageRequestOperation @implementation AFImageRequestOperation
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFImageRequestOperation *)imageRequestOperationWithRequest:(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 = ^ {
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 = nil;
if ([[UIScreen mainScreen] scale] == 2.0) { if ([[UIScreen mainScreen] scale] == 2.0) {
CGImageRef imageRef = [[UIImage imageWithData:data] CGImage]; CGImageRef imageRef = [[UIImage imageWithData:operation.responseBody] CGImage];
image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp];
} else { } else {
image = [UIImage imageWithData:data]; image = [UIImage imageWithData:operation.responseBody];
} }
if (imageProcessingBlock) { if (imageProcessingBlock) {
@ -73,16 +75,29 @@ static dispatch_queue_t image_request_operation_processing_queue() {
dispatch_async(dispatch_get_main_queue(), ^(void) { dispatch_async(dispatch_get_main_queue(), ^(void) {
if (success) { if (success) {
success(request, response, image); 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;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/bmp", @"image/x-xbitmap", nil];
return self;
} }
@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;
}
@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,94 @@
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;
+ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error;
@end
@implementation AFJSONRequestOperation @implementation AFJSONRequestOperation
@synthesize responseJSON = _responseJSON;
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (id)JSONObjectWithData:(NSData *)data error:(NSError **)error {
success:(void (^)(id JSON))success id JSON = nil;
{
return [self operationWithRequest:urlRequest success:success failure:nil]; #if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
if ([NSJSONSerialization class]) {
JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];
} else {
JSON = [[JSONDecoder decoder] objectWithData:data error:error];
}
#else
JSON = [[JSONDecoder decoder] objectWithData:data error:error];
#endif
return JSON;
} }
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(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 = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease];
if (!error) { operation.completionBlock = ^ {
if (acceptableStatusCodes && ![acceptableStatusCodes containsIndex:[response statusCode]]) { if (operation.error) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[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]]) {
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 = [self JSONObjectWithData:operation.responseBody error:&error];
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3
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 (error) {
if (failure) { if (failure) {
failure(request, response, JSONError); failure(operation.request, operation.response, error);
} }
} else { } else {
if (success) { if (success) {
success(request, response, JSON); success(operation.request, operation.response, JSON);
} }
} }
}); });
}); });
} }
}]; };
return operation;
} }
+ (NSIndexSet *)defaultAcceptableStatusCodes { - (id)initWithRequest:(NSURLRequest *)urlRequest {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil];
return self;
} }
+ (NSSet *)defaultAcceptableContentTypes { - (void)dealloc {
return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; [_responseJSON release];
[super dealloc];
}
- (id)responseJSON {
if (!_responseJSON && self.response && self.responseBody) {
self.responseJSON = [[self class] JSONObjectWithData:self.responseBody error:nil];
}
return _responseJSON;
} }
@end @end

View file

@ -48,8 +48,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;
} }

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 *_responseBody;
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 *responseBody;
@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,368 @@
// 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";
}
}
static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOperationState 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 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 *responseBody;
@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;
- (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 responseBody = _responseBody;
@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.request = urlRequest;
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.state = AFHTTPOperationReadyState;
return self;
}
- (void)dealloc {
[_runLoopModes release];
[_request release];
[_response release];
[_error release];
[_responseBody release];
[_responseString release];
[_dataAccumulator release];
[_outputStream release]; _outputStream = nil;
[_connection release]; _connection = nil;
[_uploadProgress release];
[_downloadProgress release];
[super dealloc];
}
- (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.state == state) {
return;
}
if (!AFOperationStateTransitionIsValid(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];
switch (state) {
case AFHTTPOperationExecutingState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
break;
case AFHTTPOperationFinishedState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
break;
default:
break;
}
}
- (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.responseBody) {
NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName));
self.responseString = [[[NSString alloc] initWithData:self.responseBody 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 {
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 {
[super cancel];
self.cancelled = YES;
[self.connection cancel];
}
- (void)finish {
self.state = AFHTTPOperationFinishedState;
}
#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.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];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
@end

View file

@ -97,7 +97,7 @@ 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(), ^{ dispatch_async(dispatch_get_main_queue(), ^{
if (success) { if (success) {

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 */; };
@ -33,6 +34,8 @@
/* 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>"; };
@ -221,6 +224,8 @@
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 */,
@ -335,6 +340,7 @@
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 */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
}; };