From 251ce062f2159de90f78926c33cecd87e85d0342 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Fri, 16 Sep 2011 10:36:36 -0500 Subject: [PATCH 01/24] Stashing XML Request Operation --- AFNetworking/AFJSONRequestOperation.m | 2 +- .../project.pbxproj | 6 + Example/AFXMLRequestOperation.h | 23 ++++ Example/AFXMLRequestOperation.m | 111 ++++++++++++++++++ 4 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 Example/AFXMLRequestOperation.h create mode 100644 Example/AFXMLRequestOperation.m diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 0baabd8..5987a0c 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -28,7 +28,7 @@ static dispatch_queue_t af_json_request_operation_processing_queue; static dispatch_queue_t json_request_operation_processing_queue() { if (af_json_request_operation_processing_queue == NULL) { - af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.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; diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index b61798d..26a50bb 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -18,6 +18,7 @@ F874B5DE13E0AA6500B28E3E /* AFRestClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CE13E0AA6500B28E3E /* AFRestClient.m */; }; F874B5DF13E0AA6500B28E3E /* UIImage+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CF13E0AA6500B28E3E /* UIImage+AFNetworking.m */; }; F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */; }; + F8870C0F1423A15900BCD863 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */; }; F8D25D191396A9D300CF3BD6 /* placeholder-stamp.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D171396A9D300CF3BD6 /* placeholder-stamp.png */; }; F8D25D1A1396A9D300CF3BD6 /* placeholder-stamp@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D181396A9D300CF3BD6 /* placeholder-stamp@2x.png */; }; F8DA09D21396ABED0057D0CC /* AFGowallaAPIClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */; }; @@ -58,6 +59,8 @@ F874B5D613E0AA6500B28E3E /* AFRestClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = AFRestClient.h; path = ../AFNetworking/AFRestClient.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; F874B5D713E0AA6500B28E3E /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImage+AFNetworking.h"; path = "../AFNetworking/UIImage+AFNetworking.h"; sourceTree = ""; }; F874B5D813E0AA6500B28E3E /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "../AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + F8870C0D1423A15800BCD863 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFXMLRequestOperation.h; sourceTree = ""; }; + F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = ""; }; F8D25D101396A9C400CF3BD6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; F8D25D111396A9C400CF3BD6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; F8D25D131396A9C400CF3BD6 /* TTTLocationFormatter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TTTLocationFormatter.h; sourceTree = ""; }; @@ -247,6 +250,8 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, + F8870C0D1423A15800BCD863 /* AFXMLRequestOperation.h */, + F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */, F874B5D613E0AA6500B28E3E /* AFRestClient.h */, F874B5CE13E0AA6500B28E3E /* AFRestClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, @@ -361,6 +366,7 @@ F85CE2D413EC478F00BFAE01 /* NSString+AFNetworking.m in Sources */, F85CE2DC13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m in Sources */, F85CE55513EC759200BFAE01 /* NSData+AFNetworking.m in Sources */, + F8870C0F1423A15900BCD863 /* AFXMLRequestOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Example/AFXMLRequestOperation.h b/Example/AFXMLRequestOperation.h new file mode 100644 index 0000000..72b5221 --- /dev/null +++ b/Example/AFXMLRequestOperation.h @@ -0,0 +1,23 @@ +// AFXMLRequestOperation.h + +#import "AFHTTPRequestOperation.h" + +@interface AFXMLRequestOperation : AFHTTPRequestOperation + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success; + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success + failure:(void (^)(NSError *error))failure; + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes + acceptableContentTypes:(NSSet *)acceptableContentTypes + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id XML))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + ++ (NSIndexSet *)defaultAcceptableStatusCodes; ++ (NSSet *)defaultAcceptableContentTypes; + +@end diff --git a/Example/AFXMLRequestOperation.m b/Example/AFXMLRequestOperation.m new file mode 100644 index 0000000..a1c03ae --- /dev/null +++ b/Example/AFXMLRequestOperation.m @@ -0,0 +1,111 @@ +// 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 + +static dispatch_queue_t af_xml_request_operation_processing_queue; +static dispatch_queue_t xml_request_operation_processing_queue() { + if (af_xml_request_operation_processing_queue == NULL) { + af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0); + } + + return af_xml_request_operation_processing_queue; +} + +@implementation AFXMLRequestOperation + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success +{ + return [self operationWithRequest:urlRequest success:success failure:nil]; +} + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success + failure:(void (^)(NSError *error))failure +{ + return [self operationWithRequest:urlRequest acceptableStatusCodes:[self defaultAcceptableStatusCodes] acceptableContentTypes:[self defaultAcceptableContentTypes] success:^(NSURLRequest *request, NSHTTPURLResponse *response, id XML) { + if (success) { + success(XML); + } + } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { + if (failure) { + failure(error); + } + }]; +} + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes + acceptableContentTypes:(NSSet *)acceptableContentTypes + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + return [self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { + if (!error) { + if (![acceptableStatusCodes containsIndex:[response statusCode]]) { + 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 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) { + failure(request, response, error); + } + } else if ([data length] == 0) { + if (success) { + success(request, response, nil); + } + } else { + dispatch_async(xml_request_operation_processing_queue(), ^(void) { + id XML = nil; + NSError *XMLError = nil; + + + }); + } + }]; +} + ++ (NSIndexSet *)defaultAcceptableStatusCodes { + return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; +} + ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; +} + +@end From 561df45eb76fcc1377056cc87616adfa070f6470 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 4 Oct 2011 00:13:12 -0500 Subject: [PATCH 02/24] Initial working implementation of new candidate class structure --- AFNetworking/AFHTTPClient.m | 4 +- AFNetworking/AFHTTPRequestOperation.h | 102 +---- AFNetworking/AFHTTPRequestOperation.m | 395 +++--------------- AFNetworking/AFImageRequestOperation.h | 14 +- AFNetworking/AFImageRequestOperation.m | 47 ++- AFNetworking/AFJSONRequestOperation.h | 68 +-- AFNetworking/AFJSONRequestOperation.m | 132 +++--- .../AFNetworkActivityIndicatorManager.m | 4 +- AFNetworking/AFURLConnectionOperation.h | 97 +++++ AFNetworking/AFURLConnectionOperation.m | 368 ++++++++++++++++ AFNetworking/UIImageView+AFNetworking.m | 2 +- .../project.pbxproj | 6 + 12 files changed, 656 insertions(+), 583 deletions(-) create mode 100644 AFNetworking/AFURLConnectionOperation.h create mode 100644 AFNetworking/AFURLConnectionOperation.m diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 0c828c6..b2b5041 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -228,11 +228,11 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS success:(void (^)(id object))success 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) { success(JSON); } - } failure:^(NSHTTPURLResponse *response, NSError *error) { + } failure:^(__unused NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { if (failure) { failure(response, error); } diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 0823a48..283753b 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -21,26 +21,10 @@ // THE SOFTWARE. #import +#import "AFURLConnectionOperation.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 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. + `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. # Subclassing Notes @@ -50,7 +34,7 @@ extern NSString * const AFHTTPOperationDidFinishNotification; ## 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 @@ -70,82 +54,42 @@ extern NSString * const AFHTTPOperationDidFinishNotification; @see NSOperation @see NSURLConnection */ -@interface AFHTTPRequestOperation : NSOperation { -@private - NSSet *_runLoopModes; - - NSURLConnection *_connection; - NSURLRequest *_request; - NSHTTPURLResponse *_response; - NSError *_error; - - NSData *_responseBody; - NSInteger _totalBytesRead; - NSMutableData *_dataAccumulator; - NSOutputStream *_outputStream; +@interface AFHTTPRequestOperation : AFURLConnectionOperation { +@private + NSIndexSet *_acceptableStatusCodes; + NSSet *_acceptableContentTypes; } -@property (nonatomic, retain) NSSet *runLoopModes; - -@property (readonly, nonatomic, retain) NSURLRequest *request; @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 ///--------------------------------------- -/** - Creates and returns an `AFHTTPRequestOperation` object and sets the specified completion callback. - - @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. - - @return A new HTTP request operation - */ -+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion; ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +///------------------------------- +/// @name Validating HTTP Response +///------------------------------- /** - 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 - inputStream:(NSInputStream *)inputStream - outputStream:(NSOutputStream *)outputStream - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion; - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- +- (BOOL)hasAcceptableStatusCode; /** - 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; +- (BOOL)hasAcceptableContentType; @end diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index f0b05aa..dee3043 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -22,381 +22,86 @@ #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 () -@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) 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 @implementation AFHTTPRequestOperation -@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 totalBytesRead = _totalBytesRead; -@synthesize dataAccumulator = _dataAccumulator; -@synthesize outputStream = _outputStream; -@synthesize uploadProgress = _uploadProgress; -@synthesize downloadProgress = _downloadProgress; -@synthesize completion = _completion; +@dynamic error; +@dynamic response; +@synthesize acceptableStatusCodes = _acceptableStatusCodes; +@synthesize acceptableContentTypes = _acceptableContentTypes; -static NSThread *_networkRequestThread = nil; - -+ (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 *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - AFHTTPRequestOperation *operation = [[[self alloc] init] autorelease]; - operation.request = urlRequest; - operation.completion = completion; + AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; + operation.completionBlock = ^ { + if (operation.error) { + if (failure) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.request, operation.response, operation.error); + }); + } + } else { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, operation.responseBody); + }); + } + } + }; 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]; +- (id)initWithRequest:(NSURLRequest *)request { + self = [super initWithRequest:request]; if (!self) { - return nil; + return nil; } - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - self.state = AFHTTPOperationReadyState; - + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + return self; } - (void)dealloc { - [_runLoopModes release]; - - [_request release]; - [_response release]; - [_responseBody release]; - [_dataAccumulator release]; - [_outputStream release]; _outputStream = nil; - - [_connection release]; _connection = nil; - - [_uploadProgress release]; - [_downloadProgress release]; - [_completion release]; + [_acceptableStatusCodes release]; [super dealloc]; } -- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block { - self.uploadProgress = block; +- (NSHTTPURLResponse *)response { + return (NSHTTPURLResponse *)[super response]; } -- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setState:(AFHTTPOperationState)state { - if (self.state == state) { - 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 { - [self willChangeValueForKey:@"isCancelled"]; - _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]]; +- (NSError *)error { + 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]; } - } else { - [self.dataAccumulator appendData:data]; } - if (self.downloadProgress) { - self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength); - } + return [super error]; } -- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection { - if (self.outputStream) { - [self.outputStream close]; - } else { - self.responseBody = [NSData dataWithData:self.dataAccumulator]; - [_dataAccumulator release]; _dataAccumulator = nil; - } - - [self finish]; +- (BOOL)hasAcceptableStatusCode { + return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]]; } -- (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; +- (BOOL)hasAcceptableContentType { + return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]]; } @end diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 77760a5..8639bfc 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -40,8 +40,8 @@ @return A new image request operation */ -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success; ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(UIImage *image))success; /** Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. @@ -54,10 +54,10 @@ @return A new image request operation */ -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock - cacheName:(NSString *)cacheNameOrNil - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock + cacheName:(NSString *)cacheNameOrNil + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 0e4d702..097acd8 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -26,7 +26,7 @@ static dispatch_queue_t af_image_request_operation_processing_queue; static dispatch_queue_t image_request_operation_processing_queue() { if (af_image_request_operation_processing_queue == NULL) { - af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.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; @@ -34,38 +34,40 @@ static dispatch_queue_t image_request_operation_processing_queue() { @implementation AFImageRequestOperation -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + 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) { success(image); } } failure:nil]; } -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock cacheName:(NSString *)cacheNameOrNil success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 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) { - if (error) { + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { - failure(request, response, error); + failure(operation.request, operation.response, operation.error); }); } } else { - UIImage *image = nil; + UIImage *image = nil; 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]; } else { - image = [UIImage imageWithData:data]; - } + image = [UIImage imageWithData:operation.responseBody]; + } if (imageProcessingBlock) { image = imageProcessingBlock(image); @@ -73,16 +75,29 @@ static dispatch_queue_t image_request_operation_processing_queue() { dispatch_async(dispatch_get_main_queue(), ^(void) { if (success) { - success(request, response, image); + success(operation.request, operation.response, image); } }); - if ([request cachePolicy] != NSURLCacheStorageNotAllowed) { - [[AFImageCache sharedImageCache] cacheImage:image forURL:[request URL] cacheName:cacheNameOrNil]; + if ([operation.request cachePolicy] != NSURLCacheStorageNotAllowed) { + [[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 diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index 91e47dc..96b890f 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -29,44 +29,18 @@ @see NSOperation @see AFHTTPRequestOperation */ -@interface AFJSONRequestOperation : AFHTTPRequestOperation +@interface AFJSONRequestOperation : AFHTTPRequestOperation { +@private + id _responseJSON; +} + +@property (readonly, nonatomic, retain) id responseJSON; + ///--------------------------------------- /// @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. @@ -78,29 +52,7 @@ @return A new JSON request operation */ -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes - acceptableContentTypes:(NSSet *)acceptableContentTypes - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success - 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; - ++ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; @end diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 2698a08..5ba411b 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -28,108 +28,94 @@ static dispatch_queue_t af_json_request_operation_processing_queue; static dispatch_queue_t json_request_operation_processing_queue() { if (af_json_request_operation_processing_queue == NULL) { - af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.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; } +@interface AFJSONRequestOperation () +@property (readwrite, nonatomic, retain) id responseJSON; + ++ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; +@end + @implementation AFJSONRequestOperation +@synthesize responseJSON = _responseJSON; -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id JSON))success -{ - return [self operationWithRequest:urlRequest success:success failure:nil]; ++ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { + id JSON = 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 - 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 - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure ++ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - return (AFJSONRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { - if (!error) { - if (acceptableStatusCodes && ![acceptableStatusCodes containsIndex:[response statusCode]]) { - 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) { + AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; + operation.completionBlock = ^ { + if (operation.error) { if (failure) { - dispatch_async(dispatch_get_main_queue(), ^{ - failure(request, response, error); - }); - } - } else if ([data length] == 0) { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^{ - success(request, response, nil); + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.request, operation.response, operation.error); }); } } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { - id JSON = nil; - NSError *JSONError = nil; -#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 + NSError *error = nil; + id JSON = [self JSONObjectWithData:operation.responseBody error:&error]; dispatch_async(dispatch_get_main_queue(), ^(void) { - if (JSONError) { + if (error) { if (failure) { - failure(request, response, JSONError); + failure(operation.request, operation.response, error); } } else { if (success) { - success(request, response, JSON); + success(operation.request, operation.response, JSON); } } - }); + }); }); } - }]; + }; + + return operation; } -+ (NSIndexSet *)defaultAcceptableStatusCodes { - return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; +- (id)initWithRequest:(NSURLRequest *)urlRequest { + 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 { - return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; +- (void)dealloc { + [_responseJSON release]; + [super dealloc]; +} + +- (id)responseJSON { + if (!_responseJSON && self.response && self.responseBody) { + self.responseJSON = [[self class] JSONObjectWithData:self.responseBody error:nil]; + } + + return _responseJSON; } @end diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index efd8d34..7094ea6 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -48,8 +48,8 @@ return nil; } - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFHTTPOperationDidStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFHTTPOperationDidFinishNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; return self; } diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h new file mode 100644 index 0000000..56847d1 --- /dev/null +++ b/AFNetworking/AFURLConnectionOperation.h @@ -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 + +/** + 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 \ No newline at end of file diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m new file mode 100644 index 0000000..0dfda3e --- /dev/null +++ b/AFNetworking/AFURLConnectionOperation.m @@ -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 diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index 6e128dc..6d0a10e 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -97,7 +97,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { 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]) { dispatch_async(dispatch_get_main_queue(), ^{ if (success) { diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index f91b2df..198fb15 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* 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 */; }; F874B5DA13E0AA6500B28E3E /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CA13E0AA6500B28E3E /* AFImageCache.m */; }; F874B5DB13E0AA6500B28E3E /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */; }; @@ -33,6 +34,8 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = ../AFNetworking/AFURLConnectionOperation.h; sourceTree = ""; }; + F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = ""; }; F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = ""; }; F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = ""; }; @@ -221,6 +224,8 @@ F8E469941395744600DB05C8 /* AFNetworking */ = { isa = PBXGroup; children = ( + F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */, + F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */, F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */, F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, @@ -335,6 +340,7 @@ F874B5DD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m in Sources */, F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */, F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */, + F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From b85c59516d7309a2ca78a095e731a35a4d9da521 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 4 Oct 2011 00:41:32 -0500 Subject: [PATCH 03/24] Don't execute completion block if cancelled --- AFNetworking/AFHTTPRequestOperation.m | 4 ++++ AFNetworking/AFImageRequestOperation.m | 4 ++++ AFNetworking/AFURLConnectionOperation.m | 6 +++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index dee3043..422cd1f 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -38,6 +38,10 @@ { AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 097acd8..70bfd59 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -53,6 +53,10 @@ static dispatch_queue_t image_request_operation_processing_queue() { AFImageRequestOperation *operation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + dispatch_async(image_request_operation_processing_queue(), ^(void) { if (operation.error) { if (failure) { diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 0dfda3e..9a97541 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -274,6 +274,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)cancel { + if ([self isFinished]) { + return; + } + [super cancel]; self.cancelled = YES; @@ -282,7 +286,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)finish { - self.state = AFHTTPOperationFinishedState; + self.state = AFHTTPOperationFinishedState; } #pragma mark - NSURLConnectionDelegate From c0cba6748a9fbb6d201ef4637c35dc67ab0fae16 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 11:26:51 -0500 Subject: [PATCH 04/24] Refactoring state transition logic for AFURLConnectionOperation --- AFNetworking/AFURLConnectionOperation.m | 66 ++++++++++++------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 9a97541..8500a33 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -51,29 +51,6 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState 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; @@ -88,6 +65,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; +- (BOOL)shouldTransitionToState:(AFOperationState)state; - (void)operationDidStart; - (void)finish; @end @@ -135,10 +113,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp return nil; } - self.request = urlRequest; - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; + self.request = urlRequest; + self.state = AFHTTPOperationReadyState; return self; @@ -185,11 +163,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)setState:(AFOperationState)state { - if (self.state == state) { - return; - } - - if (!AFOperationStateTransitionIsValid(self.state, state)) { + if (![self shouldTransitionToState:state]) { return; } @@ -214,6 +188,30 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } } +- (BOOL)shouldTransitionToState:(AFOperationState)state { + switch (self.state) { + case AFHTTPOperationReadyState: + switch (state) { + case AFHTTPOperationExecutingState: + return YES; + case AFHTTPOperationFinishedState: + return [self isCancelled]; + default: + return NO; + } + case AFHTTPOperationExecutingState: + switch (state) { + case AFHTTPOperationFinishedState: + return YES; + default: + return NO; + } + case AFHTTPOperationFinishedState: + default: + return NO; + } +} + - (void)setCancelled:(BOOL)cancelled { [self willChangeValueForKey:@"isCancelled"]; _cancelled = cancelled; @@ -273,6 +271,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp [self.connection start]; } +- (void)finish { + self.state = AFHTTPOperationFinishedState; +} + - (void)cancel { if ([self isFinished]) { return; @@ -285,10 +287,6 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp [self.connection cancel]; } -- (void)finish { - self.state = AFHTTPOperationFinishedState; -} - #pragma mark - NSURLConnectionDelegate - (void)connection:(NSURLConnection *)__unused connection From ccdc5f2d9b98db81c3063e9dfa85de8ea0b51e4d Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:36:45 -0500 Subject: [PATCH 05/24] Approaching a reasonable design for restructuring AFHTTPRequestOperation and subclasses --- AFNetworking/AFHTTPClient.h | 7 ++-- AFNetworking/AFHTTPClient.m | 14 +++---- AFNetworking/AFHTTPRequestOperation.h | 6 +++ AFNetworking/AFHTTPRequestOperation.m | 7 ++-- AFNetworking/AFImageRequestOperation.h | 7 +++- AFNetworking/AFImageRequestOperation.m | 51 +++++++++++++++++++------ AFNetworking/AFJSONRequestOperation.h | 4 +- AFNetworking/AFJSONRequestOperation.m | 19 ++++++--- AFNetworking/AFURLConnectionOperation.h | 2 +- AFNetworking/AFURLConnectionOperation.m | 13 ++++--- 10 files changed, 89 insertions(+), 41 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 7ac8177..c095d28 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -183,9 +183,9 @@ @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. */ -- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)request - success:(void (^)(id object))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; +- (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; ///--------------------------------- /// @name Cancelling HTTP Operations @@ -322,3 +322,4 @@ */ - (void)appendString:(NSString *)string; @end + diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index b2b5041..05f989a 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -224,9 +224,9 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS return request; } -- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id object))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +- (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) { if (success) { @@ -257,7 +257,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { 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 @@ -266,7 +266,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { 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 @@ -275,7 +275,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { 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 @@ -284,7 +284,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters]; - [self enqueueHTTPOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure]; } @end diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 283753b..714c1a4 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -23,6 +23,11 @@ #import #import "AFURLConnectionOperation.h" +@protocol AFHTTPClientRequestOperation ++ (BOOL)canInitWithRequest:(NSURLRequest *)request; ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; +@end + /** `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. @@ -58,6 +63,7 @@ @private NSIndexSet *_acceptableStatusCodes; NSSet *_acceptableContentTypes; + NSError *_HTTPError; } @property (readonly, nonatomic, retain) NSHTTPURLResponse *response; diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 422cd1f..5e8bd60 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -27,10 +27,9 @@ @end @implementation AFHTTPRequestOperation -@dynamic error; -@dynamic response; @synthesize acceptableStatusCodes = _acceptableStatusCodes; @synthesize acceptableContentTypes = _acceptableContentTypes; +@synthesize error = _HTTPError; + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success @@ -51,7 +50,7 @@ } else { if (success) { dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, operation.responseBody); + success(operation.request, operation.response, operation.responseData); }); } } @@ -81,7 +80,7 @@ } - (NSError *)error { - if (self.response && ![super error]) { + 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]; diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 8639bfc..b7ee9bb 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -30,7 +30,12 @@ @see NSOperation @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. diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 70bfd59..a1062b4 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -32,7 +32,26 @@ static dispatch_queue_t image_request_operation_processing_queue() { return af_image_request_operation_processing_queue; } +@interface AFImageRequestOperation () +@property (readwrite, nonatomic, retain) UIImage *responseImage; + ++ (UIImage *)imageWithData:(NSData *)data error:(NSError **)error ; +@end + @implementation AFImageRequestOperation +@synthesize responseImage = _responseImage; + ++ (UIImage *)imageWithData:(NSData *)data error:(NSError **)__unused error { + UIImage *image = nil; + 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]; + } + + return image; +} + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success @@ -64,24 +83,19 @@ static dispatch_queue_t image_request_operation_processing_queue() { failure(operation.request, operation.response, operation.error); }); } - } else { - UIImage *image = nil; - if ([[UIScreen mainScreen] scale] == 2.0) { - CGImageRef imageRef = [[UIImage imageWithData:operation.responseBody] CGImage]; - image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; - } else { - image = [UIImage imageWithData:operation.responseBody]; - } + } else { + UIImage *image = [[self class] imageWithData:operation.responseData error:nil]; if (imageProcessingBlock) { image = imageProcessingBlock(image); } - dispatch_async(dispatch_get_main_queue(), ^(void) { - if (success) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, image); - } - }); + }); + } if ([operation.request cachePolicy] != NSURLCacheStorageNotAllowed) { [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil]; @@ -104,4 +118,17 @@ static dispatch_queue_t image_request_operation_processing_queue() { return self; } +- (void)dealloc { + [_responseImage release]; + [super dealloc]; +} + +- (UIImage *)responseImage { + if (!_responseImage && [self isFinished]) { + self.responseImage = [[self class] imageWithData:self.responseData error:nil]; + } + + return _responseImage; +} + @end diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index 96b890f..08d1aee 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -31,12 +31,12 @@ */ @interface AFJSONRequestOperation : AFHTTPRequestOperation { @private - id _responseJSON; + id _responseJSON; + NSError *_JSONError; } @property (readonly, nonatomic, retain) id responseJSON; - ///--------------------------------------- /// @name Creating JSON Request Operations ///--------------------------------------- diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 5ba411b..a820212 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -36,12 +36,14 @@ static dispatch_queue_t json_request_operation_processing_queue() { @interface AFJSONRequestOperation () @property (readwrite, nonatomic, retain) id responseJSON; +@property (readwrite, nonatomic, retain) NSError *error; + (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; @end @implementation AFJSONRequestOperation @synthesize responseJSON = _responseJSON; +@synthesize error = _JSONError; + (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { id JSON = nil; @@ -55,7 +57,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { #else JSON = [[JSONDecoder decoder] objectWithData:data error:error]; #endif - + return JSON; } @@ -65,6 +67,10 @@ static dispatch_queue_t json_request_operation_processing_queue() { { AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { @@ -74,10 +80,11 @@ static dispatch_queue_t json_request_operation_processing_queue() { } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { NSError *error = nil; - id JSON = [self JSONObjectWithData:operation.responseBody error:&error]; + id JSON = [self JSONObjectWithData:operation.responseData error:&error]; + operation.error = error; dispatch_async(dispatch_get_main_queue(), ^(void) { - if (error) { + if (operation.error) { if (failure) { failure(operation.request, operation.response, error); } @@ -111,8 +118,10 @@ static dispatch_queue_t json_request_operation_processing_queue() { } - (id)responseJSON { - if (!_responseJSON && self.response && self.responseBody) { - self.responseJSON = [[self class] JSONObjectWithData:self.responseBody error:nil]; + if (!_responseJSON && [self isFinished]) { + NSError *error = nil; + self.responseJSON = [[self class] JSONObjectWithData:self.responseData error:nil]; + self.error = error; } return _responseJSON; diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 56847d1..9c7ba9a 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -61,7 +61,7 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; @property (readonly, nonatomic, retain) NSURLResponse *response; @property (readonly, nonatomic, retain) NSError *error; -@property (readonly, nonatomic, retain) NSData *responseBody; +@property (readonly, nonatomic, retain) NSData *responseData; @property (readonly, nonatomic, copy) NSString *responseString; @property (nonatomic, retain) NSInputStream *inputStream; diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8500a33..8540ad1 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -58,7 +58,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @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, retain) NSData *responseData; @property (readwrite, nonatomic, copy) NSString *responseString; @property (readwrite, nonatomic, assign) NSInteger totalBytesRead; @property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator; @@ -78,7 +78,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @synthesize request = _request; @synthesize response = _response; @synthesize error = _error; -@synthesize responseBody = _responseBody; +@synthesize responseData = _responseBody; @synthesize responseString = _responseString; @synthesize totalBytesRead = _totalBytesRead; @synthesize dataAccumulator = _dataAccumulator; @@ -207,8 +207,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { return NO; } case AFHTTPOperationFinishedState: - default: return NO; + default: + return YES; } } @@ -223,9 +224,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } - (NSString *)responseString { - if (!_responseString && self.response && self.responseBody) { + if (!_responseString && self.response && self.responseData) { NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName)); - self.responseString = [[[NSString alloc] initWithData:self.responseBody encoding:textEncoding] autorelease]; + self.responseString = [[[NSString alloc] initWithData:self.responseData encoding:textEncoding] autorelease]; } return _responseString; @@ -336,7 +337,7 @@ didReceiveResponse:(NSURLResponse *)response if (self.outputStream) { [self.outputStream close]; } else { - self.responseBody = [NSData dataWithData:self.dataAccumulator]; + self.responseData = [NSData dataWithData:self.dataAccumulator]; [_dataAccumulator release]; _dataAccumulator = nil; } From c2e5ca2726e5d32d483210302653bbf0d86717bd Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:47:51 -0500 Subject: [PATCH 06/24] Renaming _responseBody ivar to _responseData --- AFNetworking/AFURLConnectionOperation.h | 2 +- AFNetworking/AFURLConnectionOperation.m | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 9c7ba9a..8c620aa 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -49,7 +49,7 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; NSHTTPURLResponse *_response; NSError *_error; - NSData *_responseBody; + NSData *_responseData; NSInteger _totalBytesRead; NSMutableData *_dataAccumulator; NSOutputStream *_outputStream; diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8540ad1..9f89eda 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -78,7 +78,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @synthesize request = _request; @synthesize response = _response; @synthesize error = _error; -@synthesize responseData = _responseBody; +@synthesize responseData = _responseData; @synthesize responseString = _responseString; @synthesize totalBytesRead = _totalBytesRead; @synthesize dataAccumulator = _dataAccumulator; @@ -129,7 +129,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [_response release]; [_error release]; - [_responseBody release]; + [_responseData release]; [_responseString release]; [_dataAccumulator release]; [_outputStream release]; _outputStream = nil; From 94f08de1d522611f4f2c98dc4ab61d634ba08c30 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:52:28 -0500 Subject: [PATCH 07/24] Adding mime types for other UIImage-supported file-types --- AFNetworking/AFImageRequestOperation.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index a1062b4..fe39825 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -113,7 +113,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/bmp", @"image/x-xbitmap", nil]; + self.acceptableContentTypes = [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]; return self; } From 2c478758a2c5cf0b3d5e9ba08762ca80c5f79ef5 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 14:14:52 -0500 Subject: [PATCH 08/24] Adding Property List request operation Refactoring implementation of AFHTTPRequestOperation and subclasses --- AFNetworking/AFHTTPRequestOperation.m | 1 + AFNetworking/AFImageRequestOperation.m | 23 ++-- AFNetworking/AFJSONRequestOperation.m | 37 +++--- AFNetworking/AFPropertyListRequestOperation.h | 46 +++++++ AFNetworking/AFPropertyListRequestOperation.m | 116 ++++++++++++++++++ .../project.pbxproj | 6 + 6 files changed, 191 insertions(+), 38 deletions(-) create mode 100644 AFNetworking/AFPropertyListRequestOperation.h create mode 100644 AFNetworking/AFPropertyListRequestOperation.m diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 5e8bd60..8646873 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -72,6 +72,7 @@ - (void)dealloc { [_acceptableStatusCodes release]; + [_HTTPError release]; [super dealloc]; } diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index fe39825..81e2fef 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -34,25 +34,11 @@ static dispatch_queue_t image_request_operation_processing_queue() { @interface AFImageRequestOperation () @property (readwrite, nonatomic, retain) UIImage *responseImage; - -+ (UIImage *)imageWithData:(NSData *)data error:(NSError **)error ; @end @implementation AFImageRequestOperation @synthesize responseImage = _responseImage; -+ (UIImage *)imageWithData:(NSData *)data error:(NSError **)__unused error { - UIImage *image = nil; - 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]; - } - - return image; -} - + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success { @@ -84,7 +70,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { }); } } else { - UIImage *image = [[self class] imageWithData:operation.responseData error:nil]; + UIImage *image = operation.responseImage; if (imageProcessingBlock) { image = imageProcessingBlock(image); @@ -125,7 +111,12 @@ static dispatch_queue_t image_request_operation_processing_queue() { - (UIImage *)responseImage { if (!_responseImage && [self isFinished]) { - self.responseImage = [[self class] imageWithData:self.responseData error:nil]; + 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; diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index a820212..b3a65e3 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -37,35 +37,17 @@ static dispatch_queue_t json_request_operation_processing_queue() { @interface AFJSONRequestOperation () @property (readwrite, nonatomic, retain) id responseJSON; @property (readwrite, nonatomic, retain) NSError *error; - -+ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; @end @implementation AFJSONRequestOperation @synthesize responseJSON = _responseJSON; @synthesize error = _JSONError; -+ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { - id JSON = 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 *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; + AFJSONRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { if ([operation isCancelled]) { return; @@ -80,13 +62,13 @@ static dispatch_queue_t json_request_operation_processing_queue() { } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { NSError *error = nil; - id JSON = [self JSONObjectWithData:operation.responseData error:&error]; + id JSON = operation.responseJSON; operation.error = error; dispatch_async(dispatch_get_main_queue(), ^(void) { if (operation.error) { if (failure) { - failure(operation.request, operation.response, error); + failure(operation.request, operation.response, operation.error); } } else { if (success) { @@ -114,13 +96,24 @@ static dispatch_queue_t json_request_operation_processing_queue() { - (void)dealloc { [_responseJSON release]; + [_JSONError release]; [super dealloc]; } - (id)responseJSON { if (!_responseJSON && [self isFinished]) { NSError *error = nil; - self.responseJSON = [[self class] JSONObjectWithData:self.responseData 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; } diff --git a/AFNetworking/AFPropertyListRequestOperation.h b/AFNetworking/AFPropertyListRequestOperation.h new file mode 100644 index 0000000..9c2db3e --- /dev/null +++ b/AFNetworking/AFPropertyListRequestOperation.h @@ -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 +#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 diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m new file mode 100644 index 0000000..9d3847f --- /dev/null +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -0,0 +1,116 @@ +// 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; +@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; +} + +- (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; +} + +@end diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 198fb15..8b1bd1c 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -30,6 +30,7 @@ F8E469671395739D00DB05C8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469661395739D00DB05C8 /* Foundation.framework */; }; F8E469691395739D00DB05C8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469681395739D00DB05C8 /* CoreGraphics.framework */; }; F8E469DF13957DD500DB05C8 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469DE13957DD500DB05C8 /* CoreLocation.framework */; }; + F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */; }; F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FBFA97142AA238001409DB /* AFHTTPClient.m */; }; /* End PBXBuildFile section */ @@ -74,6 +75,8 @@ 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; }; 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 = ""; }; + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = ""; }; F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = ""; }; F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = ""; }; /* End PBXFileReference section */ @@ -234,6 +237,8 @@ F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F874B5D213E0AA6500B28E3E /* AFImageCache.h */, F874B5CA13E0AA6500B28E3E /* AFImageCache.m */, F874B5D513E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.h */, @@ -341,6 +346,7 @@ F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */, F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */, F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */, + F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From c2be31d4fa9acca15f21a91ca2804e7164b33f77 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 15:44:51 -0500 Subject: [PATCH 09/24] First implementation of protocol for AFHTTPClient to register classes to automatically determine the appropriate operation to create Wrapping AFURLConnectionOperation -setCompletionBlock: with blockSelf release pattern to avoid retain cycle --- AFNetworking/AFHTTPClient.h | 7 ++ AFNetworking/AFHTTPClient.m | 39 ++++++++--- AFNetworking/AFHTTPRequestOperation.h | 15 +++-- AFNetworking/AFHTTPRequestOperation.m | 66 +++++++++++-------- AFNetworking/AFImageRequestOperation.m | 23 +++++++ AFNetworking/AFJSONRequestOperation.m | 22 +++++++ AFNetworking/AFPropertyListRequestOperation.m | 22 +++++++ AFNetworking/AFURLConnectionOperation.m | 14 +++- AFNetworking/UIImageView+AFNetworking.m | 2 +- .../project.pbxproj | 4 +- Example/Classes/AFGowallaAPIClient.m | 4 ++ Example/Classes/Views/SpotTableViewCell.m | 21 ++++++ 12 files changed, 191 insertions(+), 48 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index c095d28..5eb0f02 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -49,6 +49,7 @@ @private NSURL *_baseURL; NSStringEncoding _stringEncoding; + NSMutableArray *_registeredHTTPOperationClassNames; NSMutableDictionary *_defaultHeaders; NSOperationQueue *_operationQueue; } @@ -96,6 +97,12 @@ */ - (id)initWithBaseURL:(NSURL *)url; +///---------------------------------- +/// @name Managing HTTP Operations +///---------------------------------- + +- (BOOL)registerHTTPOperationClass:(Class)operationClass; + ///---------------------------------- /// @name Managing HTTP Header Values ///---------------------------------- diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 05f989a..b936e95 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -77,6 +77,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @interface AFHTTPClient () @property (readwrite, nonatomic, retain) NSURL *baseURL; +@property (readwrite, nonatomic, retain) NSMutableArray *registeredHTTPOperationClassNames; @property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue; @end @@ -84,6 +85,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @implementation AFHTTPClient @synthesize baseURL = _baseURL; @synthesize stringEncoding = _stringEncoding; +@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; @synthesize defaultHeaders = _defaultHeaders; @synthesize operationQueue = _operationQueue; @@ -101,6 +103,8 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS self.stringEncoding = NSUTF8StringEncoding; + self.registeredHTTPOperationClassNames = [NSMutableArray array]; + self.defaultHeaders = [NSMutableDictionary dictionary]; // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 @@ -124,11 +128,28 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS - (void)dealloc { [_baseURL release]; + [_registeredHTTPOperationClassNames release]; [_defaultHeaders release]; [_operationQueue release]; [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 { return [self.defaultHeaders valueForKey:header]; } @@ -228,16 +249,16 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { - AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) { - if (success) { - success(JSON); + AFHTTPRequestOperation *operation = nil; + NSString *className = nil; + 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:^(__unused NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { - if (failure) { - failure(response, error); - } - }]; - + } + [self.operationQueue addOperation:operation]; } diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 714c1a4..0ac8678 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -23,9 +23,12 @@ #import #import "AFURLConnectionOperation.h" -@protocol AFHTTPClientRequestOperation -+ (BOOL)canInitWithRequest:(NSURLRequest *)request; +@protocol AFHTTPClientOperation ++ (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 /** @@ -59,7 +62,7 @@ @see NSOperation @see NSURLConnection */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation { +@interface AFHTTPRequestOperation : AFURLConnectionOperation { @private NSIndexSet *_acceptableStatusCodes; NSSet *_acceptableContentTypes; @@ -80,9 +83,9 @@ /// @name Creating HTTP Request Operations ///--------------------------------------- -+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; +//+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest +// success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success +// failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; ///------------------------------- /// @name Validating HTTP Response diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 8646873..7ed0025 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -31,34 +31,6 @@ @synthesize acceptableContentTypes = _acceptableContentTypes; @synthesize error = _HTTPError; -+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure -{ - AFHTTPRequestOperation *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 { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, operation.responseData); - }); - } - } - }; - - return operation; -} - - (id)initWithRequest:(NSURLRequest *)request { self = [super initWithRequest:request]; if (!self) { @@ -108,4 +80,42 @@ return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]]; } +#pragma mark - AFHTTPClientOperation + ++ (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 +{ + AFHTTPRequestOperation *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.response, operation.error); + }); + } + } else { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.responseData); + }); + } + } + }; + + return operation; +} + @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 81e2fef..ba68b23 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -122,4 +122,27 @@ static dispatch_queue_t image_request_operation_processing_queue() { return _responseImage; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [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 *acceptablePathExtensions = [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [acceptablePathExtensions containsObject:[[request URL] pathExtension]]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (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); + }]; +} + @end diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index b3a65e3..c3373e3 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -120,4 +120,26 @@ static dispatch_queue_t json_request_operation_processing_queue() { return _responseJSON; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"json"]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (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 diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index 9d3847f..6fabbf5 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -113,4 +113,26 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { return _responsePropertyList; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"plist"]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (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 diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 9f89eda..fcc7001 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -142,6 +142,18 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [super dealloc]; } +- (void)setCompletionBlock:(void (^)(void))block { + if (!block) { + [super setCompletionBlock:nil]; + } + + __block id _blockSelf = [self retain]; + [super setCompletionBlock:^ { + block(); + [_blockSelf autorelease]; + }]; +} + - (NSInputStream *)inputStream { return self.request.HTTPBodyStream; } @@ -194,8 +206,6 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { switch (state) { case AFHTTPOperationExecutingState: return YES; - case AFHTTPOperationFinishedState: - return [self isCancelled]; default: return NO; } diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index 6d0a10e..de894d5 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -78,7 +78,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 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 { if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:self.af_imageRequestOperation.request.URL])) { diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 8b1bd1c..a07cfe0 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -233,12 +233,12 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8FBFA96142AA237001409DB /* AFHTTPClient.h */, F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */, - F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, - F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F874B5D213E0AA6500B28E3E /* AFImageCache.h */, F874B5CA13E0AA6500B28E3E /* AFImageCache.m */, F874B5D513E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.h */, diff --git a/Example/Classes/AFGowallaAPIClient.m b/Example/Classes/AFGowallaAPIClient.m index 76ac24d..e83a320 100644 --- a/Example/Classes/AFGowallaAPIClient.m +++ b/Example/Classes/AFGowallaAPIClient.m @@ -22,6 +22,8 @@ #import "AFGowallaAPIClient.h" +#import "AFJSONRequestOperation.h" + // Replace this with your own API Key, available at http://api.gowalla.com/api/keys/ NSString * const kAFGowallaClientID = @"e7ccb7d3d2414eb2af4663fc91eb2793"; @@ -54,6 +56,8 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; // X-UDID HTTP Header [self setDefaultHeader:@"X-UDID" value:[[UIDevice currentDevice] uniqueIdentifier]]; + [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; + return self; } diff --git a/Example/Classes/Views/SpotTableViewCell.m b/Example/Classes/Views/SpotTableViewCell.m index c8feb4c..b576281 100644 --- a/Example/Classes/Views/SpotTableViewCell.m +++ b/Example/Classes/Views/SpotTableViewCell.m @@ -43,6 +43,7 @@ self.detailTextLabel.backgroundColor = self.backgroundColor; self.imageView.backgroundColor = self.backgroundColor; + self.imageView.contentMode = UIViewContentModeScaleAspectFit; self.selectionStyle = UITableViewCellSelectionStyleGray; @@ -73,4 +74,24 @@ 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 From 9b1c1f285cba569abb7626d2fc9e115e9b837331 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 10:15:58 -0500 Subject: [PATCH 10/24] Checking for cancellation early in -operationDidStart --- AFNetworking/AFURLConnectionOperation.m | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index fcc7001..353a12e 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -271,6 +271,11 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } - (void)operationDidStart { + if ([self isCancelled]) { + [self finish]; + return; + } + self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; From c1dbf407be8ca0877c00a0ee95622605405dbfe9 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 10:43:48 -0500 Subject: [PATCH 11/24] [Issue #65] Adding slight delay when hiding network activity indicator, to avoid flickering --- .../AFNetworkActivityIndicatorManager.h | 1 + .../AFNetworkActivityIndicatorManager.m | 30 +++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.h b/AFNetworking/AFNetworkActivityIndicatorManager.h index 4cd8908..9df6098 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.h +++ b/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -29,6 +29,7 @@ @private NSInteger _activityCount; BOOL _enabled; + NSTimer *_activityIndicatorVisibilityTimer; } /** diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index 7094ea6..f24b7c0 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -24,13 +24,21 @@ #import "AFHTTPRequestOperation.h" +static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25; + @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, retain) NSTimer *activityIndicatorVisibilityTimer; +@property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateNetworkActivityIndicatorVisibility; @end @implementation AFNetworkActivityIndicatorManager @synthesize activityCount = _activityCount; +@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; @synthesize enabled = _enabled; +@dynamic networkActivityIndicatorVisible; + (AFNetworkActivityIndicatorManager *)sharedManager { static AFNetworkActivityIndicatorManager *_sharedManager = nil; @@ -50,13 +58,16 @@ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; - + return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; + [_activityIndicatorVisibilityTimer invalidate]; + [_activityIndicatorVisibilityTimer release]; _activityIndicatorVisibilityTimer = nil; + [super dealloc]; } @@ -66,10 +77,25 @@ [self didChangeValueForKey:@"activityCount"]; 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 { @synchronized(self) { self.activityCount += 1; From 6f20f84ef15d10fe59c38770563158459f40416d Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 14:33:16 -0500 Subject: [PATCH 12/24] Adding AFHTTPClientParameterEncoding @property to AFHTTPClient, which determines the method of encoding an NSDictionary of parameters for the body of an HTTP request Minor refactoring of AFRestClient --- AFNetworking/AFHTTPClient.h | 15 +++ AFNetworking/AFHTTPClient.m | 102 ++++++++++++++---- .../project.pbxproj | 4 +- 3 files changed, 98 insertions(+), 23 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 5eb0f02..2e31c27 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -25,6 +25,12 @@ @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. @@ -49,6 +55,7 @@ @private NSURL *_baseURL; NSStringEncoding _stringEncoding; + AFHTTPClientParameterEncoding _parameterEncoding; NSMutableArray *_registeredHTTPOperationClassNames; NSMutableDictionary *_defaultHeaders; NSOperationQueue *_operationQueue; @@ -68,6 +75,11 @@ */ @property (nonatomic, assign) NSStringEncoding stringEncoding; +/** + + */ +@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding; + /** The operation queue which manages operations enqueued by the HTTP client. */ @@ -193,6 +205,9 @@ - (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)request success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; +/** + */ +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation; ///--------------------------------- /// @name Cancelling HTTP Operations diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index b936e95..ce9a9ad 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -22,6 +22,9 @@ #import "AFHTTPClient.h" #import "AFJSONRequestOperation.h" +#import "JSONKit.h" + +#include static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; @@ -40,6 +43,8 @@ static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY" #pragma mark - +static NSUInteger const kAFHTTPClientDefaultMaxConcurrentOperationCount = 4; + static NSString * AFBase64EncodedStringFromString(NSString *string) { NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSUInteger length = [data length]; @@ -69,10 +74,52 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) { return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease]; } -static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { +static NSString * AFURLEncodedStringFromString(NSString *string) { 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 () @@ -85,6 +132,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @implementation AFHTTPClient @synthesize baseURL = _baseURL; @synthesize stringEncoding = _stringEncoding; +@synthesize parameterEncoding = _parameterEncoding; @synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; @synthesize defaultHeaders = _defaultHeaders; @synthesize operationQueue = _operationQueue; @@ -102,6 +150,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS self.baseURL = url; self.stringEncoding = NSUTF8StringEncoding; + self.parameterEncoding = AFJSONParameterEncoding; self.registeredHTTPOperationClassNames = [NSMutableArray array]; @@ -121,7 +170,7 @@ 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.operationQueue = [[[NSOperationQueue alloc] init] autorelease]; - [self.operationQueue setMaxConcurrentOperationCount:2]; + [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount]; return self; } @@ -177,31 +226,34 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS path:(NSString *)path parameters:(NSDictionary *)parameters { - NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; - NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; + [request setHTTPMethod:method]; + [request setAllHTTPHeaderFields:self.defaultHeaders]; - 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 (parameters) { 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 { NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); - [headers setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forKey:@"Content-Type"]; - [request setHTTPBody:[queryString dataUsingEncoding:self.stringEncoding]]; + switch (self.parameterEncoding) { + 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; } @@ -258,7 +310,15 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS operation = [class HTTPRequestOperationWithRequest:urlRequest success:success failure:failure]; } } + + if (!operation) { + operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:urlRequest success:success failure:failure]; + } + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation { [self.operationQueue addOperation:operation]; } diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 09644af..53eb182 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -236,10 +236,10 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, - F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, - F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */, F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8FBFA96142AA237001409DB /* AFHTTPClient.h */, F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, From 62596c25b9a8ecbf5f8c828ce12b806fb41d7deb Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 09:40:11 -0500 Subject: [PATCH 13/24] [Issue #72] Fixing HTTP Client method of constructing URLs from a path with respect to a base url --- AFNetworking/AFHTTPClient.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index ce9a9ad..94a99e8 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -226,7 +226,7 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { path:(NSString *)path parameters:(NSDictionary *)parameters { - NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSURL *url = [self.baseURL URLByAppendingPathComponent:path]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; [request setHTTPMethod:method]; [request setAllHTTPHeaderFields:self.defaultHeaders]; From 120247718d35a4329be60482b8a434abce991b21 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 09:40:32 -0500 Subject: [PATCH 14/24] Removing delegate argument to class method constructor --- AFNetworking/AFXMLRequestOperation.h | 1 - AFNetworking/AFXMLRequestOperation.m | 2 -- 2 files changed, 3 deletions(-) diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index a81e740..390153e 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -31,7 +31,6 @@ @property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser; + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - delegate:(id )delegate success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index f7a105c..00dd1fb 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -32,7 +32,6 @@ @synthesize responseXMLParser = _responseXMLParser; + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - delegate:(id )delegate success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { @@ -50,7 +49,6 @@ } } else { NSXMLParser *XMLParser = operation.responseXMLParser; - XMLParser.delegate = delegate; if (success) { success(operation.request, operation.response, XMLParser); } From 263e2f3d5c06c88fd88d60222e96c634c45d8dcc Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:04:57 -0500 Subject: [PATCH 15/24] [Issue #59] Removing unnecessary dispatch in UIImageView category --- AFNetworking/UIImageView+AFNetworking.m | 30 +++++++++++-------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index de894d5..ba880c4 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -81,7 +81,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 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; } else { [self cancelImageRequestOperation]; @@ -99,26 +99,22 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp 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]) { - dispatch_async(dispatch_get_main_queue(), ^{ - if (success) { - success(request, response, image); - } - - if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { - self.image = image; - } else { - self.image = placeholderImage; - } - }); + if (success) { + success(request, response, image); + } + + if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { + self.image = image; + } else { + self.image = placeholderImage; + } } } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { self.af_imageRequestOperation = nil; - dispatch_async(dispatch_get_main_queue(), ^{ - if (failure) { - failure(request, response, error); - } - }); + if (failure) { + failure(request, response, error); + } }]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; From b7564e9f5aa6b14bec0861bb7720b93d0b650353 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:41:29 -0500 Subject: [PATCH 16/24] Refactoring implementation of AFHTTPRequest subclasses to fulfill AFHTTPClientOperation protocol --- AFNetworking/AFHTTPRequestOperation.m | 23 +------------- AFNetworking/AFImageRequestOperation.m | 21 ++++++++----- AFNetworking/AFJSONRequestOperation.m | 20 ++++++++----- AFNetworking/AFPropertyListRequestOperation.m | 18 +++++++---- AFNetworking/AFXMLRequestOperation.m | 30 ++++++++++++++++++- 5 files changed, 68 insertions(+), 44 deletions(-) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 7ed0025..a842c95 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -94,28 +94,7 @@ success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { - AFHTTPRequestOperation *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.response, operation.error); - }); - } - } else { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.responseData); - }); - } - } - }; - - return operation; + return nil; } @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index ba68b23..9e7e956 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -34,6 +34,9 @@ static dispatch_queue_t image_request_operation_processing_queue() { @interface AFImageRequestOperation () @property (readwrite, nonatomic, retain) UIImage *responseImage; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFImageRequestOperation @@ -93,13 +96,21 @@ static dispatch_queue_t image_request_operation_processing_queue() { 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 = [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]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -125,13 +136,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [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 *acceptablePathExtensions = [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [acceptablePathExtensions containsObject:[[request URL] pathExtension]]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index c3373e3..61a4cbf 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -37,6 +37,9 @@ static dispatch_queue_t 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 @@ -83,13 +86,21 @@ static dispatch_queue_t json_request_operation_processing_queue() { return operation; } ++ (NSSet *)defaultAcceptableContentTypes { + 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 = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -123,12 +134,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"json"]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index 6fabbf5..eb2f7c4 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -35,6 +35,9 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { @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 @@ -81,6 +84,14 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { 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) { @@ -116,12 +127,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"plist"]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 00dd1fb..057b2e5 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -26,6 +26,9 @@ @interface AFXMLRequestOperation () @property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFXMLRequestOperation @@ -58,13 +61,21 @@ 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 = [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -82,4 +93,21 @@ return _responseXMLParser; } +#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 From b28b99dd16882bea93e6ef357e90f9a9fad2f70c Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:51:23 -0500 Subject: [PATCH 17/24] Moving AFHTTPClientOperation protocol to AFHTTPClient Refactoring #import statements --- AFNetworking/AFHTTPClient.h | 13 ++++++++++++- AFNetworking/AFHTTPRequestOperation.h | 9 +-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 2e31c27..b0d3c14 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -21,8 +21,9 @@ // THE SOFTWARE. #import -#import "AFHTTPRequestOperation.h" +@class AFHTTPRequestOperation; +@protocol AFHTTPClientOperation; @protocol AFMultipartFormData; typedef enum { @@ -288,6 +289,16 @@ typedef enum { #pragma mark - +@protocol AFHTTPClientOperation ++ (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:`. */ diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 0ac8678..8e66e54 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -22,14 +22,7 @@ #import #import "AFURLConnectionOperation.h" - -@protocol AFHTTPClientOperation -+ (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 +#import "AFHTTPClient.h" /** `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. From 998f7bb701cbe896ba271074105a61b6bfbadc9b Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 11:06:31 -0500 Subject: [PATCH 18/24] nil-ing out responseXMLParser delegate if AFXMLRequestOperation is cancelled --- AFNetworking/AFXMLRequestOperation.m | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 057b2e5..e958e1c 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -93,6 +93,14 @@ return _responseXMLParser; } +#pragma mark - NSOperation + +- (void)cancel { + [super cancel]; + + self.responseXMLParser.delegate = nil; +} + #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { From db3dddb03be167620bab001c3bd58e7f18aba046 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 11:07:14 -0500 Subject: [PATCH 19/24] Setting _responseXMLParser delegate to nil in AFXMLRequestOperation -dealloc --- AFNetworking/AFXMLRequestOperation.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index e958e1c..9f7b72c 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -81,7 +81,9 @@ } - (void)dealloc { + _responseXMLParser.delegate = nil; [_responseXMLParser release]; + [super dealloc]; } From ce9872965c85b490dcba3eb3f504b6dc312dc87f Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:05:22 -0500 Subject: [PATCH 20/24] [Issue #56] Fixing 'The Dealloc Problem' --- AFNetworking/AFURLConnectionOperation.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 353a12e..8015bd6 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -147,10 +147,10 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [super setCompletionBlock:nil]; } - __block id _blockSelf = [self retain]; + __block id _blockSelf = self; [super setCompletionBlock:^ { block(); - [_blockSelf autorelease]; + [_blockSelf setCompletionBlock:nil]; }]; } From 3e27e189ee16615619b9da2b92175acb5a1535ec Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:05:47 -0500 Subject: [PATCH 21/24] Adding missing release for _acceptableContentTypes in AFHTTPRequestOperation -dealloc --- AFNetworking/AFHTTPRequestOperation.m | 1 + 1 file changed, 1 insertion(+) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index a842c95..6f052d5 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -44,6 +44,7 @@ - (void)dealloc { [_acceptableStatusCodes release]; + [_acceptableContentTypes release]; [_HTTPError release]; [super dealloc]; } From b7724922c45706463d1208c8ae42b8c403777d92 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:06:12 -0500 Subject: [PATCH 22/24] Refactoring image request operation --- AFNetworking/AFImageRequestOperation.m | 3 +-- AFNetworking/UIImageView+AFNetworking.m | 10 +++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 9e7e956..9e2ba89 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -81,7 +81,6 @@ static dispatch_queue_t image_request_operation_processing_queue() { if (success) { dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, image); }); } @@ -90,7 +89,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil]; } } - }); + }); }; return operation; diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index ba880c4..74f718b 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -27,7 +27,7 @@ #import "AFImageCache.h" -static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOperation"; +static char kAFImageRequestOperationObjectKey; @interface UIImageView (_AFNetworking) @property (readwrite, nonatomic, retain, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; @@ -42,11 +42,11 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp @implementation UIImageView (AFNetworking) - (AFHTTPRequestOperation *)af_imageRequestOperation { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, kAFImageRequestOperationObjectKey); + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); } - (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 { @@ -97,7 +97,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { self.image = placeholderImage; - self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest: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 (success) { success(request, response, image); @@ -108,7 +108,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { self.image = placeholderImage; } - } + } } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { self.af_imageRequestOperation = nil; From f1fa6f1a6f664e9fdbceb728b9dccdf04505631a Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:18:41 -0500 Subject: [PATCH 23/24] [Issue #56] Wrapping completion block in async_dispatch to main queue --- AFNetworking/AFURLConnectionOperation.m | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8015bd6..be7e10f 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -149,8 +149,10 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { __block id _blockSelf = self; [super setCompletionBlock:^ { - block(); - [_blockSelf setCompletionBlock:nil]; + dispatch_async(dispatch_get_main_queue(), ^(void) { + block(); + [_blockSelf setCompletionBlock:nil]; + }); }]; } From 95bcd2278c0bdbf6847a7c9939beece2b32091a2 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:26:17 -0500 Subject: [PATCH 24/24] Only execute in main queue --- AFNetworking/AFURLConnectionOperation.m | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index be7e10f..30e04e8 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -149,8 +149,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { __block id _blockSelf = self; [super setCompletionBlock:^ { + block(); + dispatch_async(dispatch_get_main_queue(), ^(void) { - block(); [_blockSelf setCompletionBlock:nil]; }); }];