Skip to content

Commit

Permalink
Merge branch 'experimental-0.9'
Browse files Browse the repository at this point in the history
  • Loading branch information
mattt committed Jan 23, 2012
2 parents abc1cbf + 1635c8e commit 1c64c6c
Show file tree
Hide file tree
Showing 22 changed files with 601 additions and 453 deletions.
9 changes: 5 additions & 4 deletions AFNetworking.podspec
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
Pod::Spec.new do |s|
s.name = 'AFNetworking'
s.version = '0.8.0'
s.version = '0.9.0'
s.license = 'MIT'
s.summary = 'A delightful iOS and OS X networking framework'
s.homepage = 'https://github.com/AFNetworking/AFNetworking'
s.authors = {'Mattt Thompson' => '[email protected]', 'Scott Raymond' => '[email protected]'}
s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git',
:tag => '0.8.0' }

s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '0.9.0' }
s.source_files = 'AFNetworking'
s.clean_paths = ['iOS Example', 'Mac Example', 'AFNetworking.xcworkspace']
s.framework = 'SystemConfiguration'
end
55 changes: 49 additions & 6 deletions AFNetworking/AFHTTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,24 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
*/
- (id)initWithBaseURL:(NSURL *)url;

///----------------------------------
///-----------------------------------
/// @name Managing Reachability Status
///-----------------------------------

/**
Sets a callback to be executed when the network availability of the `baseURL` host changes.
@param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument, which is `YES` if the host is available, otherwise `NO`.
@warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (Prefix.pch).
*/
#ifdef _SYSTEMCONFIGURATION_H
- (void)setReachabilityStatusChangeBlock:(void (^)(BOOL isNetworkReachable))block;
#endif

///-------------------------------
/// @name Managing HTTP Operations
///----------------------------------
///-------------------------------

/**
Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request.
Expand Down Expand Up @@ -294,12 +309,40 @@ extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *paramete
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;

/**
Cancels all operations in the HTTP client's operation queue that match the specified HTTP method and URL.
Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path.
@param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled.
@param url The path to match for the cancelled requests.
*/
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;

///---------------------------------------
/// @name Batching HTTP Request Operations
///---------------------------------------

/**
Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
@param requests The `NSURLRequest` objects used to create and enqueue operations.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
@discussion Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters.
*/
- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;

/**
Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.
@param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`.
@param url The URL to match for the cancelled requests.
@param operations The request operations used to be batched and enqueued.
@param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.
@param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.
*/
- (void)cancelHTTPOperationsWithMethod:(NSString *)method andURL:(NSURL *)url;
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;

///---------------------------
/// @name Making HTTP Requests
Expand Down
102 changes: 100 additions & 2 deletions AFNetworking/AFHTTPClient.m
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@
#import <UIKit/UIKit.h>
#endif

#ifdef _SYSTEMCONFIGURATION_H
#import <SystemConfiguration/SystemConfiguration.h>
#endif

static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF
static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";

@interface AFMultipartFormData : NSObject <AFMultipartFormData> {
Expand All @@ -48,6 +53,15 @@ - (id)initWithStringEncoding:(NSStringEncoding)encoding;

#pragma mark -

#ifdef _SYSTEMCONFIGURATION_H
typedef SCNetworkReachabilityRef AFNetworkReachabilityRef;
#else
typedef id AFNetworkReachabilityRef;
#endif

typedef void (^AFNetworkReachabilityStatusBlock)(BOOL isNetworkReachable);
typedef void (^AFCompletionBlock)(void);

static NSUInteger const kAFHTTPClientDefaultMaxConcurrentOperationCount = 4;

static NSString * AFBase64EncodedStringFromString(NSString *string) {
Expand Down Expand Up @@ -132,6 +146,8 @@ @interface AFHTTPClient ()
@property (readwrite, nonatomic, retain) NSMutableArray *registeredHTTPOperationClassNames;
@property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders;
@property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue;
@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability;
@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock;
@end

@implementation AFHTTPClient
Expand All @@ -141,6 +157,8 @@ @implementation AFHTTPClient
@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames;
@synthesize defaultHeaders = _defaultHeaders;
@synthesize operationQueue = _operationQueue;
@synthesize networkReachability = _networkReachability;
@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock;

+ (AFHTTPClient *)clientWithBaseURL:(NSURL *)url {
return [[[self alloc] initWithBaseURL:url] autorelease];
Expand Down Expand Up @@ -186,9 +204,43 @@ - (void)dealloc {
[_registeredHTTPOperationClassNames release];
[_defaultHeaders release];
[_operationQueue release];
[_networkReachabilityStatusBlock release];
if (_networkReachability) {
CFRelease(_networkReachability);
}

[super dealloc];
}

- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue];
}

#pragma mark -

#ifdef _SYSTEMCONFIGURATION_H
static void AFReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) {
if (info) {
AFNetworkReachabilityStatusBlock block = (AFNetworkReachabilityStatusBlock)info;
BOOL isNetworkReachable = (flags & kSCNetworkReachabilityFlagsReachable);
block(isNetworkReachable);
}
}

- (void)setReachabilityStatusChangeBlock:(void (^)(BOOL isNetworkReachable))block {
if (_networkReachability) {
SCNetworkReachabilityUnscheduleFromRunLoop(_networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
CFRelease(_networkReachability);
}

self.networkReachabilityStatusBlock = block;
self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]);
SCNetworkReachabilityContext context = {0, self.networkReachabilityStatusBlock, NULL, NULL, NULL};
SCNetworkReachabilitySetCallback(self.networkReachability, AFReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), (CFStringRef)NSRunLoopCommonModes);
}
#endif

#pragma mark -

- (BOOL)registerHTTPOperationClass:(Class)operationClass {
Expand Down Expand Up @@ -326,18 +378,64 @@ - (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlR
return operation;
}

#pragma mark -

- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
[self.operationQueue addOperation:operation];
}

- (void)cancelHTTPOperationsWithMethod:(NSString *)method andURL:(NSURL *)url {
- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path {
for (AFHTTPRequestOperation *operation in [self.operationQueue operations]) {
if ([[[operation request] HTTPMethod] isEqualToString:method] && [[[operation request] URL] isEqual:url]) {
if ((!method || [method isEqualToString:[[operation request] HTTPMethod]]) && [path isEqualToString:[[[operation request] URL] path]]) {
[operation cancel];
}
}
}

- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)requests
progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURLRequest *request in requests) {
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil];
[mutableOperations addObject:operation];
}

[self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock];
}

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock
{
NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
if (completionBlock) {
completionBlock(operations);
}
}];

[self.operationQueue addOperation:batchedOperation];

NSPredicate *finishedOperationPredicate = [NSPredicate predicateWithFormat:@"isFinished == YES"];

for (AFHTTPRequestOperation *operation in operations) {
AFCompletionBlock originalCompletionBlock = [[operation.completionBlock copy] autorelease];
operation.completionBlock = ^{
if (progressBlock) {
progressBlock([[batchedOperation.dependencies filteredArrayUsingPredicate:finishedOperationPredicate] count], [batchedOperation.dependencies count]);
}

if (originalCompletionBlock) {
originalCompletionBlock();
}
};

[batchedOperation addDependency:operation];
[self enqueueHTTPRequestOperation:operation];
}
}

#pragma mark -

- (void)getPath:(NSString *)path
Expand Down
11 changes: 3 additions & 8 deletions AFNetworking/AFHTTPRequestOperation.m
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@

@interface AFHTTPRequestOperation ()
@property (readwrite, nonatomic, retain) NSError *HTTPError;
@property (readonly, nonatomic, assign) BOOL hasContent;
@end

@implementation AFHTTPRequestOperation
Expand Down Expand Up @@ -62,7 +61,7 @@ - (NSError *)error {
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];

self.HTTPError = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease];
} else if ([self hasContent] && ![self hasAcceptableContentType]) { // Don't invalidate content type if there is no content
} else if ([self.responseData length] > 0 && ![self hasAcceptableContentType]) { // Don't invalidate content type if there is no content
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];
Expand All @@ -71,17 +70,13 @@ - (NSError *)error {
}
}

if (_HTTPError) {
return _HTTPError;
if (self.HTTPError) {
return self.HTTPError;
} else {
return [super error];
}
}

- (BOOL)hasContent {
return [self.responseData length] > 0;
}

- (BOOL)hasAcceptableStatusCode {
return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]];
}
Expand Down
76 changes: 0 additions & 76 deletions AFNetworking/AFImageCache.h

This file was deleted.

Loading

0 comments on commit 1c64c6c

Please sign in to comment.