Merge branch 'experimental-0.7'

Conflicts:
	AFNetworking/AFHTTPClient.h
This commit is contained in:
Mattt Thompson 2011-10-12 11:41:02 -05:00
commit ed60b11987
68 changed files with 7760 additions and 845 deletions

View file

@ -1,13 +1,13 @@
Pod::Spec.new do
name 'AFNetworking'
version '0.6.1'
summary 'A delightful iOS networking library with NSOperations and block-based callbacks'
version '0.7.0'
summary 'A delightful iOS and OS X networking framework'
homepage 'https://github.com/gowalla/AFNetworking'
authors 'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@gowalla.com'
source :git => 'https://github.com/gowalla/AFNetworking.git',
:tag => '0.6.1'
:tag => '0.7.0'
platforms 'iOS'
platforms 'iOS', 'OSX'
sdk '>= 4.0'
source_files 'AFNetworking'

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:iOS Example/AFNetworking iOS Example.xcodeproj">
</FileRef>
<FileRef
location = "group:Mac Example/AFNetworking Mac Example.xcodeproj">
</FileRef>
</Workspace>

View file

@ -21,34 +21,53 @@
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
@class AFHTTPRequestOperation;
@protocol AFHTTPClientOperation;
@protocol AFMultipartFormData;
/**
`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.
Method used to encode parameters into request body
*/
typedef enum {
AFFormURLParameterEncoding,
AFJSONParameterEncoding,
AFPropertyListParameterEncoding,
} AFHTTPClientParameterEncoding;
In its default implementation, `AFHTTPClient` sets the following HTTP headers:
/**
`AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.
## Automatic Content Parsing
Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`. See `AFHTTPClientOperation` for further details.
## Subclassing Notes
In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.
## Methods to Override
To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`.
To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `enqueueHTTPRequestOperationWithRequest:success:failure`.
## Default Headers
By default, `AFHTTPClient` sets the following HTTP headers:
- `Accept: application/json`
- `Accept-Encoding: gzip`
- `Accept-Language: #{[NSLocale preferredLanguages]}, en-us;q=0.8`
- `User-Agent: #{generated user agent}`
You can override these HTTP headers or define new ones using `setDefaultHeader:value:`.
# Subclassing Notes
It is strongly recommended that you create an `AFHTTPClient` subclass for each website or web application that your application communicates with, and in each subclass, defining a method that returns a singleton object that acts as single a shared HTTP client that holds authentication credentials and other configuration for the entire application.
## Methods to Override
If an `AFHTTPClient` wishes to change the way request parameters are encoded, then the base implementation of `requestWithMethod:path:parameters:` should be overridden. Otherwise, it should be sufficient to take the `super` implementation, and configure the resulting `NSMutableURLRequest` object accordingly.
*/
@interface AFHTTPClient : NSObject {
@private
NSURL *_baseURL;
NSStringEncoding _stringEncoding;
AFHTTPClientParameterEncoding _parameterEncoding;
NSMutableArray *_registeredHTTPOperationClassNames;
NSMutableDictionary *_defaultHeaders;
NSOperationQueue *_operationQueue;
}
@ -67,6 +86,11 @@
*/
@property (nonatomic, assign) NSStringEncoding stringEncoding;
/**
The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body. This is `AFFormURLParameterEncoding` by default.
*/
@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding;
/**
The operation queue which manages operations enqueued by the HTTP client.
*/
@ -90,12 +114,38 @@
@param url The base URL for the HTTP client. This argument must not be nil.
@discussion This is the designated initializer for `AFHTTPClient`
@discussion This is the designated initializer.
@return The newly-initialized HTTP client
*/
- (id)initWithBaseURL:(NSURL *)url;
///----------------------------------
/// @name Managing HTTP Operations
///----------------------------------
/**
Attempts to register a class conforming to the `AFHTTPClientOperation` protocol, adding it to a chain to automatically generate request operations from a URL request.
@param The class conforming to the `AFHTTPClientOperation` protocol to register
@return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` does not conform to the `AFHTTPCLientOperation` protocol.
@discussion When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the chain.
@see `AFHTTPClientOperation`
*/
- (BOOL)registerHTTPOperationClass:(Class)operationClass;
/**
Unregisteres the specified class conforming to the `AFHTTPClientOperation` protocol.
@param The class conforming to the `AFHTTPClientOperation` protocol to unregister
@discussion After this method is invoked, `operationClass` is no longer consulted when `requestWithMethod:path:parameters` is invoked.
*/
- (void)unregisterHTTPOperationClass:(Class)operationClass;
///----------------------------------
/// @name Managing HTTP Header Values
///----------------------------------
@ -142,13 +192,17 @@
///-------------------------------
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and path. If the HTTP method is `GET`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. If `POST`, `PUT`, or `DELETE`, the parameters will be encoded into a `application/x-www-form-urlencoded` HTTP body.
Creates an `NSMutableURLRequest` object with the specified HTTP method and path. By default, this method scans through the registered operation classes (in reverse order of when they were specified), until finding one that can handle the specified request.
If the HTTP method is `GET`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body.
@param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`.
@param path The path to be appended to the HTTP client's base URL and used as the request URL.
@param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body.
@return An `NSMutableURLRequest` object
@see AFHTTPClientOperation
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
@ -164,6 +218,8 @@
@see AFMultipartFormData
@warning An exception will be raised if the specified method is not `POST`, `PUT` or `DELETE`.
@return An `NSMutableURLRequest` object
*/
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
@ -179,13 +235,23 @@
/**
Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
In order to determine what kind of operation is enqueued, each registered subclass conforming to the `AFHTTPClient` protocol is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`.
@param request The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is an object created from the response data of request.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a single argument, which is the `NSError` object describing the network or parsing error that occurred.
@param success A block object to be executed when the request operation finishes successfully. 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. This block has no return value and takes a single argument, which is the `NSError` object describing the network or parsing error that occurred.
@see `AFHTTPClientOperation`
*/
- (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;
/**
Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue.
@param operation The HTTP request operation to be enqueued.
*/
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation;
///---------------------------------
/// @name Cancelling HTTP Operations
@ -266,8 +332,39 @@
#pragma mark -
/**
The `AFHTTPClientOperation` protocol defines the methods used for the automatic content parsing functionality of `AFHTTPClient`.
@see `AFHTTPClient -registerHTTPOperationClass:`
*/
@protocol AFHTTPClientOperation
/**
A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`.
@param urlRequest The request that is determined to be supported or not supported for this class.
*/
+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest;
/**
Constructs and initializes an operation with success and failure callbacks.
@param urlRequest The request used by the operation connection.
@param success A block object to be executed when the operation finishes successfully. The block has no return value and takes a single argument, the response object from the request.
@param failure A block object to be executed when the operation finishes unsuccessfully. The block has no return value and takes two arguments: the response received from the server, and the error describing the network or parsing error that occurred.
*/
+ (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:`.
@see `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`
*/
@protocol AFMultipartFormData
@ -298,16 +395,6 @@
*/
- (void)appendPartWithFileData:(NSData *)data mimeType:(NSString *)mimeType name:(NSString *)name;
/**
Appends the HTTP header `Content-Disposition: file; filename=#{filename}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary.
@param fileURL The URL for the local file to have its contents appended to the form data. This parameter must not be `nil`.
@param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`.
@param fileName The filename to be associated with the file contents. This parameter must not be `nil`.
@param error If an error occurs, upon return contains an `NSError` object that describes the problem.
*/
- (void)appendPartWithFile:(NSURL *)fileURL mimeType:(NSString *)mimeType fileName:(NSString *)fileName error:(NSError **)error;
/**
Appends encoded data to the form data.
@ -322,3 +409,4 @@
*/
- (void)appendString:(NSString *)string;
@end

View file

@ -20,8 +20,18 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
#endif
#import "JSONKit.h"
static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF
static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY";
@ -40,6 +50,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,14 +81,57 @@ 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 || __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6
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 ()
@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 +139,8 @@ 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;
@ -100,12 +157,12 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
self.baseURL = url;
self.stringEncoding = NSUTF8StringEncoding;
self.parameterEncoding = AFJSONParameterEncoding;
self.registeredHTTPOperationClassNames = [NSMutableArray array];
self.defaultHeaders = [NSMutableDictionary dictionary];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
// Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
[self setDefaultHeader:@"Accept-Encoding" value:@"gzip"];
@ -113,22 +170,48 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS
NSString *preferredLanguageCodes = [[NSLocale preferredLanguages] componentsJoinedByString:@", "];
[self setDefaultHeader:@"Accept-Language" value:[NSString stringWithFormat:@"%@, en-us;q=0.8", preferredLanguageCodes]];
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
[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)]];
#if __IPHONE_OS_VERSION_MIN_REQUIRED
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@, %@ %@, %@, 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)]];
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
[self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown"]];
#endif
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
[self.operationQueue setMaxConcurrentOperationCount:2];
[self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount];
return self;
}
- (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;
}
- (void)unregisterHTTPOperationClass:(Class)operationClass {
NSString *className = NSStringFromClass(operationClass);
[self.registeredHTTPOperationClassNames removeObject:className];
}
#pragma mark -
- (NSString *)defaultValueForHeader:(NSString *)header {
return [self.defaultHeaders valueForKey:header];
}
@ -156,31 +239,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 = [self.baseURL URLByAppendingPathComponent:path];
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 ([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;
}
@ -224,20 +310,28 @@ 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 operationWithRequest:urlRequest success:^(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:^(NSHTTPURLResponse *response, NSError *error) {
if (failure) {
failure(response, error);
}
}];
}
if (!operation) {
operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:urlRequest success:success failure:failure];
}
[self enqueueHTTPRequestOperation:operation];
}
- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation {
[self.operationQueue addOperation:operation];
}
@ -257,7 +351,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 +360,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 +369,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 +378,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
@ -361,17 +455,6 @@ static inline NSString * AFMultipartFormFinalBoundary() {
[self appendPartWithHeaders:mutableHeaders body:data];
}
- (void)appendPartWithFile:(NSURL *)fileURL mimeType:(NSString *)mimeType fileName:(NSString *)fileName error:(NSError **)error {
NSData *data = [NSData dataWithContentsOfFile:[fileURL absoluteString] options:0 error:error];
if (data) {
NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary];
[mutableHeaders setValue:[NSString stringWithFormat:@"file; filename=\"%@\"", fileName] forKey:@"Content-Disposition"];
[mutableHeaders setValue:mimeType forKey:@"Content-Type"];
[self appendPartWithHeaders:mutableHeaders body:data];
}
}
- (void)appendData:(NSData *)data {
[self.mutableData appendData:data];
}

View file

@ -21,131 +21,55 @@
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFURLConnectionOperation.h"
#import "AFHTTPClient.h"
/**
Indicates an error occured in AFNetworking.
@discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain.
`AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
*/
extern NSString * const AFNetworkingErrorDomain;
/**
Posted when an operation begins executing.
*/
extern NSString * const AFHTTPOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const AFHTTPOperationDidFinishNotification;
/**
`AFHTTPRequestOperation` is an `NSOperation` that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes.
# Subclassing Notes
In cases where you don't need all of the information provided in the callback, or you want to validate and/or represent it in a different way, it makes sense to create a subclass to define this behavior.
For instance, `AFJSONRequestOperation` makes a distinction between successful and unsuccessful requests by validating the HTTP status code and content type of the response, and provides separate callbacks for both the succeeding and failing cases. As another example, `AFImageRequestOperation` offers a pared-down callback, with a single block argument that is an image object that was created from the response data.
## 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
Notably, `AFHTTPRequestOperation` does not implement any of the authentication challenge-related `NSURLConnection` delegate methods.
`AFHTTPRequestOperation` does implement the following `NSURLConnection` delegate methods:
- `connection:didReceiveResponse:`
- `connection:didReceiveData:`
- `connectionDidFinishLoading:`
- `connection:didFailWithError:`
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
If you overwrite any of the above methods, be sure to make the call to `super` first, or else it may cause unexpected results.
@see NSOperation
@see NSURLConnection
*/
@interface AFHTTPRequestOperation : NSOperation {
@interface AFHTTPRequestOperation : AFURLConnectionOperation <AFHTTPClientOperation> {
@private
NSSet *_runLoopModes;
NSURLConnection *_connection;
NSURLRequest *_request;
NSHTTPURLResponse *_response;
NSError *_error;
NSData *_responseBody;
NSInteger _totalBytesRead;
NSMutableData *_dataAccumulator;
NSOutputStream *_outputStream;
NSIndexSet *_acceptableStatusCodes;
NSSet *_acceptableContentTypes;
NSError *_HTTPError;
}
@property (nonatomic, retain) NSSet *runLoopModes;
///----------------------------------------------
/// @name Getting HTTP URL Connection Information
///----------------------------------------------
@property (readonly, nonatomic, retain) NSURLRequest *request;
/**
The last HTTP response received by the operation's connection.
*/
@property (readonly, nonatomic, retain) NSHTTPURLResponse *response;
@property (readonly, nonatomic, retain) NSError *error;
@property (readonly, nonatomic, retain) NSData *responseBody;
@property (readonly) NSString *responseString;
///---------------------------------------
/// @name Creating HTTP Request Operations
///---------------------------------------
///----------------------------------------------------------
/// @name Managing And Checking For Acceptable HTTP Responses
///----------------------------------------------------------
/**
Creates and returns an `AFHTTPRequestOperation` object and sets the specified completion callback.
Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
@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
By default, this is the range 200 to 299, inclusive.
*/
+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion;
@property (nonatomic, retain) NSIndexSet *acceptableStatusCodes;
/**
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
A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`.
*/
+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest
inputStream:(NSInputStream *)inputStream
outputStream:(NSOutputStream *)outputStream
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion;
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
@property (readonly) BOOL hasAcceptableStatusCode;
/**
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
@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
By default, this is `nil`.
*/
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block;
@property (nonatomic, retain) NSSet *acceptableContentTypes;
/**
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
A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`.
*/
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block;
@property (readonly) BOOL hasAcceptableContentType;
@end

View file

@ -22,381 +22,76 @@
#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;
@synthesize acceptableStatusCodes = _acceptableStatusCodes;
@synthesize acceptableContentTypes = _acceptableContentTypes;
@synthesize error = _HTTPError;
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 *operation = [[[self alloc] init] autorelease];
operation.request = urlRequest;
operation.completion = completion;
return operation;
}
+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest
inputStream:(NSInputStream *)inputStream
outputStream:(NSOutputStream *)outputStream
completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion
{
NSMutableURLRequest *mutableURLRequest = [[urlRequest mutableCopy] autorelease];
if (inputStream) {
[mutableURLRequest setHTTPBodyStream:inputStream];
if ([[mutableURLRequest HTTPMethod] isEqualToString:@"GET"]) {
[mutableURLRequest setHTTPMethod:@"POST"];
}
}
AFHTTPRequestOperation *operation = [self operationWithRequest:mutableURLRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, __unused NSData *data, NSError *error) {
if (completion) {
completion(request, response, error);
}
}];
operation.outputStream = outputStream;
return operation;
}
- (id)init {
self = [super init];
- (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];
[_acceptableContentTypes release];
[_HTTPError 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;
}
- (NSError *)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];
[userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey];
- (void)setState:(AFHTTPOperationState)state {
if (self.state == state) {
return;
}
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];
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]];
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
- (BOOL)hasAcceptableContentType {
return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]];
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return NO;
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
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;
return nil;
}
@end

View file

@ -23,8 +23,10 @@
#import <Foundation/Foundation.h>
#import "AFImageRequestOperation.h"
#import <Availability.h>
/**
`AFImageCache` is a subclass of `NSCache` that stores and retrieves images from cache.
`AFImageCache` is an `NSCache` that stores and retrieves images from cache.
@discussion `AFImageCache` is used to cache images for successful `AFImageRequestOperations` with the proper cache policy.
*/
@ -45,8 +47,14 @@
@return The image associated with the URL and cache name, or `nil` if not image exists.
*/
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (UIImage *)cachedImageForURL:(NSURL *)url
cacheName:(NSString *)cacheName;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSImage *)cachedImageForURL:(NSURL *)url
cacheName:(NSString *)cacheName;
#endif
/**
Stores an image into cache, associated with a given URL and cache name.
@ -55,8 +63,15 @@
@param url The URL to be associated with the image.
@param cacheName The cache name to be associated with the image in the cache. This allows for multiple versions of an image to be associated for a single URL, such as image thumbnails, for instance.
*/
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (void)cacheImage:(UIImage *)image
forURL:(NSURL *)url
cacheName:(NSString *)cacheName;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (void)cacheImage:(NSImage *)image
forURL:(NSURL *)url
cacheName:(NSString *)cacheName;
#endif
@end

View file

@ -39,12 +39,21 @@ static inline NSString * AFImageCacheKeyFromURLAndCacheName(NSURL *url, NSString
return _sharedImageCache;
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (UIImage *)cachedImageForURL:(NSURL *)url
cacheName:(NSString *)cacheName
{
return [self objectForKey:AFImageCacheKeyFromURLAndCacheName(url, cacheName)];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSImage *)cachedImageForURL:(NSURL *)url
cacheName:(NSString *)cacheName
{
return [self objectForKey:AFImageCacheKeyFromURLAndCacheName(url, cacheName)];
}
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (void)cacheImage:(UIImage *)image
forURL:(NSURL *)url
cacheName:(NSString *)cacheName
@ -55,5 +64,17 @@ static inline NSString * AFImageCacheKeyFromURLAndCacheName(NSURL *url, NSString
[self setObject:image forKey:AFImageCacheKeyFromURLAndCacheName(url, cacheName)];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (void)cacheImage:(NSImage *)image
forURL:(NSURL *)url
cacheName:(NSString *)cacheName
{
if (!image) {
return;
}
[self setObject:image forKey:AFImageCacheKeyFromURLAndCacheName(url, cacheName)];
}
#endif
@end

View file

@ -21,27 +21,64 @@
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "AFHTTPRequestOperation.h"
/**
`AFImageRequestOperation` is an `NSOperation` that wraps the callback from `AFHTTPRequestOperation` to create an image from the response body, and optionally cache the image to memory.
#import <Availability.h>
@see NSOperation
@see AFHTTPRequestOperation
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
#import <Cocoa/Cocoa.h>
#endif
/**
`AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images.
## Acceptable Content Types
By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:
- `image/tiff`
- `image/jpeg`
- `image/gif`
- `image/png`
- `image/ico`
- `image/x-icon`
- `image/bmp`
- `image/x-bmp`
- `image/x-xbitmap`
- `image/x-win-bitmap`
*/
@interface AFImageRequestOperation : AFHTTPRequestOperation
@interface AFImageRequestOperation : AFHTTPRequestOperation {
@private
#if __IPHONE_OS_VERSION_MIN_REQUIRED
UIImage *_responseImage;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
NSImage *_responseImage;
#endif
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
@property (readonly, nonatomic, retain) UIImage *responseImage;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readonly, nonatomic, retain) NSImage *responseImage;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@param urlRequest The request object to be loaded asynchronously during execution of the operation.
@param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes a single arguments, the image created from the response data of the request.
@param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single arguments, the image created from the response data of the request.
@return A new image request operation
*/
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success;
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success;
#endif
/**
Creates and returns an `AFImageRequestOperation` object and sets the specified success callback.
@ -54,10 +91,18 @@
@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;
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (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;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
cacheName:(NSString *)cacheNameOrNil
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#endif
@end

View file

@ -26,63 +26,212 @@
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;
}
@implementation AFImageRequestOperation
@interface AFImageRequestOperation ()
#if __IPHONE_OS_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) UIImage *responseImage;
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) NSImage *responseImage;
#endif
+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(UIImage *image))success
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFImageRequestOperation
@synthesize responseImage = _responseImage;
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (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
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
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSImage *image))success
{
return (AFImageRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) {
return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) {
if (success) {
success(image);
}
} failure:nil];
}
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (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
{
AFImageRequestOperation *operation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
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;
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];
}
UIImage *image = operation.responseImage;
if (imageProcessingBlock) {
image = imageProcessingBlock(image);
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (success) {
success(request, response, image);
}
});
if (success) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
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;
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock
cacheName:(NSString *)cacheNameOrNil
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
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) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
NSImage *image = operation.responseImage;
if (imageProcessingBlock) {
image = imageProcessingBlock(image);
}
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];
}
}
});
};
return operation;
}
#endif
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseImage release];
[super dealloc];
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
- (UIImage *)responseImage {
if (!_responseImage && [self isFinished]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
CGImageRef imageRef = [[UIImage imageWithData:self.responseData] CGImage];
self.responseImage = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp];
} else {
self.responseImage = [UIImage imageWithData:self.responseData];
}
}
return _responseImage;
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSImage *)responseImage {
if (!_responseImage && [self isFinished]) {
self.responseImage = [[[NSImage alloc] initWithData:self.responseData] autorelease];
}
return _responseImage;
}
#endif
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
#if __IPHONE_OS_VERSION_MIN_REQUIRED
+ (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);
}];
}
#elif __MAC_OS_X_VERSION_MIN_REQUIRED
+ (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, NSImage *image) {
success(image);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
#endif
@end

View file

@ -24,83 +24,44 @@
#import "AFHTTPRequestOperation.h"
/**
`AFJSONRequestOperation` is an `NSOperation` that wraps the callback from `AFHTTPRequestOperation` to determine the success or failure of a request based on its status code and response content type, and parse the response body into a JSON object.
`AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data.
@see NSOperation
@see AFHTTPRequestOperation
## Acceptable Content Types
By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types:
- `application/json`
- `text/json`
*/
@interface AFJSONRequestOperation : AFHTTPRequestOperation
@interface AFJSONRequestOperation : AFHTTPRequestOperation {
@private
id _responseJSON;
NSError *_JSONError;
}
///---------------------------------------
/// @name Creating JSON Request Operations
///---------------------------------------
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
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
A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success;
@property (readonly, nonatomic, retain) id responseJSON;
///----------------------------------
/// @name Creating Request Operations
///----------------------------------
/**
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:
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new 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.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param acceptableStatusCodes An `NSIndexSet` object that specifies the ranges of acceptable status codes. If you specify nil, all status codes will be considered acceptable.
@param acceptableContentTypes An `NSSet` object that specifies the acceptable content types. If you specify nil, all content types will be considered acceptable.
@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 three arguments, the request sent from the client, the response received from the server, and 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 three arguments, the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new 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

View file

@ -21,115 +21,132 @@
// THE SOFTWARE.
#import "AFJSONRequestOperation.h"
#import "JSONKit.h"
#include <Availability.h>
#import "JSONKit.h"
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;
@property (readwrite, nonatomic, retain) NSError *error;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFJSONRequestOperation
@synthesize responseJSON = _responseJSON;
@synthesize error = _JSONError;
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success
+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
return [self operationWithRequest:urlRequest success:success failure:nil];
}
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id JSON))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self operationWithRequest:urlRequest acceptableStatusCodes:[self defaultAcceptableStatusCodes] acceptableContentTypes:[self defaultAcceptableContentTypes] success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) {
if (success) {
success(JSON);
}
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
if (failure) {
failure(response, error);
}
}];
}
+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest
acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes
acceptableContentTypes:(NSSet *)acceptableContentTypes
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success
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];
}
AFJSONRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (error) {
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 = operation.responseJSON;
operation.error = error;
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (JSONError) {
if (operation.error) {
if (failure) {
failure(request, response, JSONError);
failure(operation.request, operation.response, operation.error);
}
} else {
if (success) {
success(request, response, JSON);
success(operation.request, operation.response, JSON);
}
}
});
});
}
}];
}
};
+ (NSIndexSet *)defaultAcceptableStatusCodes {
return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
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];
return [NSSet setWithObjects:@"application/json", @"text/json", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"json", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
[_responseJSON release];
[_JSONError release];
[super dealloc];
}
- (id)responseJSON {
if (!_responseJSON && [self isFinished]) {
NSError *error = nil;
#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 || __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6
if ([NSJSONSerialization class]) {
self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error];
} else {
self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error];
}
#else
self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error];
#endif
self.error = error;
}
return _responseJSON;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self JSONRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) {
success(JSON);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
@end

View file

@ -22,6 +22,11 @@
#import <Foundation/Foundation.h>
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
/**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
*/
@ -29,6 +34,7 @@
@private
NSInteger _activityCount;
BOOL _enabled;
NSTimer *_activityIndicatorVisibilityTimer;
}
/**
@ -56,3 +62,4 @@
- (void)decrementActivityCount;
@end
#endif

View file

@ -24,13 +24,22 @@
#import "AFHTTPRequestOperation.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED
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;
@ -48,8 +57,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;
}
@ -57,6 +66,9 @@
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_activityIndicatorVisibilityTimer invalidate];
[_activityIndicatorVisibilityTimer release]; _activityIndicatorVisibilityTimer = nil;
[super dealloc];
}
@ -66,10 +78,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;
@ -83,3 +110,4 @@
}
@end
#endif

View file

@ -0,0 +1,40 @@
// AFNetworking.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <Availability.h>
#import <AFNetworking/AFURLConnectionOperation.h>
#import <AFNetworking/AFHTTPRequestOperation.h>
#import <AFNetworking/AFJSONRequestOperation.h>
#import <AFNetworking/AFXMLRequestOperation.h>
#import <AFNetworking/AFPropertyListRequestOperation.h>
#import <AFNetworking/AFHTTPClient.h>
#import <AFNetworking/AFImageRequestOperation.h>
#import <AFNetworking/AFImagecache.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <AFNetworking/AFNetworkActivityIndicatorManager.h>
#import <AFNetworking/UIImageView+AFNetworking.h>
#endif

View file

@ -0,0 +1,74 @@
// AFPropertyListRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
/**
`AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data.
## Acceptable Content Types
By default, `AFPropertyListRequestOperation` accepts the following MIME types:
- `application/x-plist`
*/
@interface AFPropertyListRequestOperation : AFHTTPRequestOperation {
@private
id _responsePropertyList;
NSPropertyListFormat _propertyListFormat;
NSPropertyListReadOptions _propertyListReadOptions;
NSError *_propertyListError;
}
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An object deserialized from a plist constructed using the response data.
*/
@property (readonly, nonatomic, retain) id responsePropertyList;
///--------------------------------------
/// @name Managing Property List Behavior
///--------------------------------------
/**
One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`.
*/
@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions;
/**
Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new property list request operation
*/
+ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
@end

View file

@ -0,0 +1,143 @@
// AFPropertyListRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFPropertyListRequestOperation.h"
static dispatch_queue_t af_property_list_request_operation_processing_queue;
static dispatch_queue_t property_list_request_operation_processing_queue() {
if (af_property_list_request_operation_processing_queue == NULL) {
af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0);
}
return af_property_list_request_operation_processing_queue;
}
@interface AFPropertyListRequestOperation ()
@property (readwrite, nonatomic, retain) id responsePropertyList;
@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat;
@property (readwrite, nonatomic, retain) NSError *error;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFPropertyListRequestOperation
@synthesize responsePropertyList = _responsePropertyList;
@synthesize propertyListReadOptions = _propertyListReadOptions;
@synthesize propertyListFormat = _propertyListFormat;
@synthesize error = _propertyListError;
+ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFPropertyListRequestOperation *operation = [[[self alloc] initWithRequest:request] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (operation.error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
dispatch_async(property_list_request_operation_processing_queue(), ^(void) {
id propertyList = operation.responsePropertyList;
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (operation.error) {
if (failure) {
failure(operation.request, operation.response, operation.error);
}
} else {
if (success) {
success(operation.request, operation.response, propertyList);
}
}
});
});
}
};
return operation;
}
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/x-plist", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"plist", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
self.propertyListReadOptions = NSPropertyListImmutable;
return self;
}
- (void)dealloc {
[_responsePropertyList release];
[_propertyListError release];
[super dealloc];
}
- (id)responsePropertyList {
if (!_responsePropertyList && [self isFinished]) {
NSPropertyListFormat format;
NSError *error = nil;
self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error];
self.propertyListFormat = format;
self.error = error;
}
return _responsePropertyList;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
return [self propertyListRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id propertyList) {
success(propertyList);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
}
@end

View file

@ -0,0 +1,188 @@
// AFURLConnectionOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
/**
Indicates an error occured in AFNetworking.
@discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain.
*/
extern NSString * const AFNetworkingErrorDomain;
/**
Posted when an operation begins executing.
*/
extern NSString * const AFNetworkingOperationDidStartNotification;
/**
Posted when an operation finishes.
*/
extern NSString * const AFNetworkingOperationDidFinishNotification;
/**
`AFURLConnectionOperation` is an `NSOperation` that implements NSURLConnection delegate methods.
## Subclassing Notes
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors.
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation`, which supports specifying acceptable content types or status codes.
## NSURLConnection Delegate Methods
`AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods:
- `connection:didReceiveResponse:`
- `connection:didReceiveData:`
- `connectionDidFinishLoading:`
- `connection:didFailWithError:`
- `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:`
- `connection:willCacheResponse:`
If any of these methods are overriden in a subclass, they _must_ call the `super` implementation first.
Notably, `AFHTTPRequestOperation` does not implement any of the authentication challenge-related `NSURLConnection` delegate methods, and are thus safe to override without a call to `super`.
## Class Constructors
Class constructors, or methods that return an unowned (zero retain count) instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`.
## Callbacks and Completion Blocks
The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (e.g. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this.
@warning Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a particular workaround to mitigate retain cycles, and what Apple rather ominously refers to as "The Deallocation Problem" (See http://developer.apple.com/library/ios/technotes/tn2109/_index.html#//apple_ref/doc/uid/DTS40010274-CH1-SUBSECTION11)
*/
@interface AFURLConnectionOperation : NSOperation {
@private
NSSet *_runLoopModes;
NSURLConnection *_connection;
NSURLRequest *_request;
NSHTTPURLResponse *_response;
NSError *_error;
NSData *_responseData;
NSInteger _totalBytesRead;
NSMutableData *_dataAccumulator;
NSOutputStream *_outputStream;
}
///-------------------------------
/// @name Accessing Run Loop Modes
///-------------------------------
/**
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`.
*/
@property (nonatomic, retain) NSSet *runLoopModes;
///-----------------------------------------
/// @name Getting URL Connection Information
///-----------------------------------------
/**
The request used by the operation's connection.
*/
@property (readonly, nonatomic, retain) NSURLRequest *request;
/**
The last response received by the operation's connection.
*/
@property (readonly, nonatomic, retain) NSURLResponse *response;
/**
The error, if any, that occured in the lifecycle of the request.
*/
@property (readonly, nonatomic, retain) NSError *error;
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
The data received during the request.
*/
@property (readonly, nonatomic, retain) NSData *responseData;
/**
The string representation of the response data.
@discussion This method uses the string encoding of the response to construct a string from the response data.
*/
@property (readonly, nonatomic, copy) NSString *responseString;
///------------------------
/// @name Accessing Streams
///------------------------
/**
The input stream used to read data to be sent during the request.
@discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`.
*/
@property (nonatomic, retain) NSInputStream *inputStream;
/**
The output stream that is used to write data received until the request is finished.
@discussion By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`.
*/
@property (nonatomic, retain) NSOutputStream *outputStream;
///------------------------------------------------------
/// @name Initializing an AFURLConnectionOperation Object
///------------------------------------------------------
/**
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
@param urlRequest The request object to be used by the operation connection.
@discussion This is the designated initializer.
*/
- (id)initWithRequest:(NSURLRequest *)urlRequest;
///---------------------------------
/// @name Setting Progress Callbacks
///---------------------------------
/**
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
@param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times.
@see setDownloadProgressBlock
*/
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block;
/**
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
@param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes read since the last time the upload progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times.
@see setUploadProgressBlock
*/
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block;
@end

View file

@ -0,0 +1,384 @@
// AFURLConnectionOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFURLConnectionOperation.h"
static NSUInteger const kAFHTTPMinimumInitialDataCapacity = 1024;
static NSUInteger const kAFHTTPMaximumInitialDataCapacity = 1024 * 1024 * 8;
typedef enum {
AFHTTPOperationReadyState = 1,
AFHTTPOperationExecutingState = 2,
AFHTTPOperationFinishedState = 3,
} AFOperationState;
NSString * const AFNetworkingErrorDomain = @"com.alamofire.networking.error";
NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
typedef void (^AFURLConnectionOperationProgressBlock)(NSInteger bytes, NSInteger totalBytes, NSInteger totalBytesExpected);
static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
switch (state) {
case AFHTTPOperationReadyState:
return @"isReady";
case AFHTTPOperationExecutingState:
return @"isExecuting";
case AFHTTPOperationFinishedState:
return @"isFinished";
default:
return @"state";
}
}
@interface AFURLConnectionOperation ()
@property (readwrite, nonatomic, assign) AFOperationState state;
@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled;
@property (readwrite, nonatomic, retain) NSURLConnection *connection;
@property (readwrite, nonatomic, retain) NSURLRequest *request;
@property (readwrite, nonatomic, retain) NSURLResponse *response;
@property (readwrite, nonatomic, retain) NSError *error;
@property (readwrite, nonatomic, retain) NSData *responseData;
@property (readwrite, nonatomic, copy) NSString *responseString;
@property (readwrite, nonatomic, assign) NSInteger totalBytesRead;
@property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
- (BOOL)shouldTransitionToState:(AFOperationState)state;
- (void)operationDidStart;
- (void)finish;
@end
@implementation AFURLConnectionOperation
@synthesize state = _state;
@synthesize cancelled = _cancelled;
@synthesize connection = _connection;
@synthesize runLoopModes = _runLoopModes;
@synthesize request = _request;
@synthesize response = _response;
@synthesize error = _error;
@synthesize responseData = _responseData;
@synthesize responseString = _responseString;
@synthesize totalBytesRead = _totalBytesRead;
@synthesize dataAccumulator = _dataAccumulator;
@dynamic inputStream;
@synthesize outputStream = _outputStream;
@synthesize uploadProgress = _uploadProgress;
@synthesize downloadProgress = _downloadProgress;
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
do {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[NSRunLoop currentRunLoop] run];
[pool drain];
} while (YES);
}
+ (NSThread *)networkRequestThread {
static NSThread *_networkRequestThread = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
[_networkRequestThread start];
});
return _networkRequestThread;
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super init];
if (!self) {
return nil;
}
self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
self.request = urlRequest;
self.state = AFHTTPOperationReadyState;
return self;
}
- (void)dealloc {
[_runLoopModes release];
[_request release];
[_response release];
[_error release];
[_responseData release];
[_responseString release];
[_dataAccumulator release];
[_outputStream release]; _outputStream = nil;
[_connection release]; _connection = nil;
[_uploadProgress release];
[_downloadProgress release];
[super dealloc];
}
- (void)setCompletionBlock:(void (^)(void))block {
if (!block) {
[super setCompletionBlock:nil];
} else {
__block id _blockSelf = self;
[super setCompletionBlock:^ {
block();
[_blockSelf setCompletionBlock:nil];
}];
}
}
- (NSInputStream *)inputStream {
return self.request.HTTPBodyStream;
}
- (void)setInputStream:(NSInputStream *)inputStream {
NSMutableURLRequest *mutableRequest = [[self.request mutableCopy] autorelease];
mutableRequest.HTTPBodyStream = inputStream;
self.request = mutableRequest;
}
- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block {
self.uploadProgress = block;
}
- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block {
self.downloadProgress = block;
}
- (void)setState:(AFOperationState)state {
if (![self shouldTransitionToState:state]) {
return;
}
NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
NSString *newStateKey = AFKeyPathFromOperationState(state);
[self willChangeValueForKey:newStateKey];
[self willChangeValueForKey:oldStateKey];
_state = state;
[self didChangeValueForKey:oldStateKey];
[self didChangeValueForKey:newStateKey];
switch (state) {
case AFHTTPOperationExecutingState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
break;
case AFHTTPOperationFinishedState:
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
break;
default:
break;
}
}
- (BOOL)shouldTransitionToState:(AFOperationState)state {
switch (self.state) {
case AFHTTPOperationReadyState:
switch (state) {
case AFHTTPOperationExecutingState:
return YES;
default:
return NO;
}
case AFHTTPOperationExecutingState:
switch (state) {
case AFHTTPOperationFinishedState:
return YES;
default:
return NO;
}
case AFHTTPOperationFinishedState:
return NO;
default:
return YES;
}
}
- (void)setCancelled:(BOOL)cancelled {
[self willChangeValueForKey:@"isCancelled"];
_cancelled = cancelled;
[self didChangeValueForKey:@"isCancelled"];
if ([self isCancelled]) {
self.state = AFHTTPOperationFinishedState;
}
}
- (NSString *)responseString {
if (!_responseString && self.response && self.responseData) {
NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName));
self.responseString = [[[NSString alloc] initWithData:self.responseData encoding:textEncoding] autorelease];
}
return _responseString;
}
#pragma mark - NSOperation
- (BOOL)isReady {
return self.state == AFHTTPOperationReadyState;
}
- (BOOL)isExecuting {
return self.state == AFHTTPOperationExecutingState;
}
- (BOOL)isFinished {
return self.state == AFHTTPOperationFinishedState;
}
- (BOOL)isConcurrent {
return YES;
}
- (void)start {
if (![self isReady]) {
return;
}
self.state = AFHTTPOperationExecutingState;
[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]];
}
- (void)operationDidStart {
if ([self isCancelled]) {
[self finish];
return;
}
self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
for (NSString *runLoopMode in self.runLoopModes) {
[self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
[self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
}
[self.connection start];
}
- (void)finish {
self.state = AFHTTPOperationFinishedState;
}
- (void)cancel {
if ([self isFinished]) {
return;
}
[super cancel];
self.cancelled = YES;
[self.connection cancel];
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)__unused connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (self.uploadProgress) {
self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
}
}
- (void)connection:(NSURLConnection *)__unused connection
didReceiveResponse:(NSURLResponse *)response
{
self.response = (NSHTTPURLResponse *)response;
if (self.outputStream) {
[self.outputStream open];
} else {
NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), kAFHTTPMinimumInitialDataCapacity);
NSUInteger capacity = MIN(maxCapacity, kAFHTTPMaximumInitialDataCapacity);
self.dataAccumulator = [NSMutableData dataWithCapacity:capacity];
}
}
- (void)connection:(NSURLConnection *)__unused connection
didReceiveData:(NSData *)data
{
self.totalBytesRead += [data length];
if (self.outputStream) {
if ([self.outputStream hasSpaceAvailable]) {
const uint8_t *dataBuffer = [data bytes];
[self.outputStream write:&dataBuffer[0] maxLength:[data length]];
}
} else {
[self.dataAccumulator appendData:data];
}
if (self.downloadProgress) {
self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength);
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection {
if (self.outputStream) {
[self.outputStream close];
} else {
self.responseData = [NSData dataWithData:self.dataAccumulator];
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (void)connection:(NSURLConnection *)__unused connection
didFailWithError:(NSError *)error
{
self.error = error;
if (self.outputStream) {
[self.outputStream close];
} else {
[_dataAccumulator release]; _dataAccumulator = nil;
}
[self finish];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
if ([self isCancelled]) {
return nil;
}
return cachedResponse;
}
@end

View file

@ -0,0 +1,92 @@
// AFXMLRequestOperation.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperation.h"
#import <Availability.h>
/**
`AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data.
## Acceptable Content Types
By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types:
- `application/xml`
- `text/xml`
*/
@interface AFXMLRequestOperation : AFHTTPRequestOperation {
@private
NSXMLParser *_responseXMLParser;
#if __MAC_OS_X_VERSION_MIN_REQUIRED
NSXMLDocument *_responseXMLDocument;
#endif
NSError *_XMLError;
}
///----------------------------
/// @name Getting Response Data
///----------------------------
/**
An `NSXMLParser` object constructed from the response data.
*/
@property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser;
#if __MAC_OS_X_VERSION_MIN_REQUIRED
/**
An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error.
*/
@property (readonly, nonatomic, retain) NSXMLDocument *responseXMLDocument;
#endif
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred.
@return A new XML request operation
*/
+ (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#if __MAC_OS_X_VERSION_MIN_REQUIRED
/**
Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks.
@param urlRequest The request object to be loaded asynchronously during execution of the operation
@param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request.
@param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred.
@return A new XML request operation
*/
+ (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;
#endif
@end

View file

@ -0,0 +1,199 @@
// AFXMLRequestOperation.m
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFXMLRequestOperation.h"
#include <Availability.h>
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;
}
@interface AFXMLRequestOperation ()
@property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser;
#if __MAC_OS_X_VERSION_MIN_REQUIRED
@property (readwrite, nonatomic, retain) NSXMLDocument *responseXMLDocument;
#endif
@property (readwrite, nonatomic, retain) NSError *error;
+ (NSSet *)defaultAcceptableContentTypes;
+ (NSSet *)defaultAcceptablePathExtensions;
@end
@implementation AFXMLRequestOperation
@synthesize responseXMLParser = _responseXMLParser;
#if __MAC_OS_X_VERSION_MIN_REQUIRED
@synthesize responseXMLDocument = _responseXMLDocument;
#endif
@synthesize error = _XMLError;
+ (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFXMLRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (operation.error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
NSXMLParser *XMLParser = operation.responseXMLParser;
if (success) {
success(operation.request, operation.response, XMLParser);
}
}
};
return operation;
}
#if __MAC_OS_X_VERSION_MIN_REQUIRED
+ (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{
AFXMLRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease];
operation.completionBlock = ^ {
if ([operation isCancelled]) {
return;
}
if (operation.error) {
if (failure) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
failure(operation.request, operation.response, operation.error);
});
}
} else {
dispatch_async(xml_request_operation_processing_queue(), ^(void) {
NSXMLDocument *XMLDocument = operation.responseXMLDocument;
if (success) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
success(operation.request, operation.response, XMLDocument);
});
}
});
}
};
return operation;
}
#endif
+ (NSSet *)defaultAcceptableContentTypes {
return [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
}
+ (NSSet *)defaultAcceptablePathExtensions {
return [NSSet setWithObjects:@"xml", nil];
}
- (id)initWithRequest:(NSURLRequest *)urlRequest {
self = [super initWithRequest:urlRequest];
if (!self) {
return nil;
}
self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes];
return self;
}
- (void)dealloc {
_responseXMLParser.delegate = nil;
[_responseXMLParser release];
#if __MAC_OS_X_VERSION_MIN_REQUIRED
[_responseXMLDocument release];
#endif
[_XMLError release];
[super dealloc];
}
- (NSXMLParser *)responseXMLParser {
if (!_responseXMLParser && [self isFinished]) {
self.responseXMLParser = [[[NSXMLParser alloc] initWithData:self.responseData] autorelease];
}
return _responseXMLParser;
}
#if __MAC_OS_X_VERSION_MIN_REQUIRED
- (NSXMLDocument *)responseXMLDocument {
if (!_responseXMLDocument && [self isFinished]) {
NSError *error = nil;
self.responseXMLDocument = [[[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error] autorelease];
self.error = error;
}
return _responseXMLDocument;
}
#endif
#pragma mark - NSOperation
- (void)cancel {
[super cancel];
self.responseXMLParser.delegate = nil;
}
#pragma mark - AFHTTPClientOperation
+ (BOOL)canProcessRequest:(NSURLRequest *)request {
return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]];
}
+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest
success:(void (^)(id object))success
failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure
{
#if __MAC_OS_X_VERSION_MIN_REQUIRED
return [self XMLDocumentRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSXMLDocument *XMLDocument) {
success(XMLDocument);
} failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) {
failure(response, error);
}];
#else
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);
}];
#endif
}
@end

View file

@ -20,9 +20,14 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "AFImageRequestOperation.h"
#import <Availability.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import <UIKit/UIKit.h>
/**
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
*/
@ -53,16 +58,17 @@
@param urlRequest The url request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
@param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments, the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments, the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
@param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@discussion By default, url requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set to use HTTP pipelining, and not handle cookies. To configure url requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
*/
- (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;
- (void)cancelImageRequestOperation;
@end
#endif

View file

@ -23,11 +23,13 @@
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED
#import "UIImageView+AFNetworking.h"
#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 +44,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 {
@ -78,10 +80,10 @@ 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])) {
if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]])) {
return;
} else {
[self cancelImageRequestOperation];
@ -90,6 +92,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
UIImage *cachedImage = [[AFImageCache sharedImageCache] cachedImageForURL:[urlRequest URL] cacheName:nil];
if (cachedImage) {
self.image = cachedImage;
self.af_imageRequestOperation = nil;
if (success) {
success(nil, nil, cachedImage);
@ -97,28 +100,24 @@ 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) {
success(request, response, image);
}
if (success) {
success(request, response, image);
}
if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) {
self.image = image;
} else {
self.image = placeholderImage;
}
});
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];
@ -130,3 +129,4 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp
}
@end
#endif

View file

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "1.0">
</Bucket>

View file

@ -0,0 +1,418 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
F87A159F1444926300318955 /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A159E1444926300318955 /* AFURLConnectionOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F87A15A21444926A00318955 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A15A11444926900318955 /* AFXMLRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F87A15A51444927300318955 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F87A15CD1444A30800318955 /* AFGowallaAPIClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A15C61444A30800318955 /* AFGowallaAPIClient.m */; };
F87A15CE1444A30800318955 /* NearbySpotsController.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A15C91444A30800318955 /* NearbySpotsController.m */; };
F87A15CF1444A30800318955 /* Spot.m in Sources */ = {isa = PBXBuildFile; fileRef = F87A15CC1444A30800318955 /* Spot.m */; };
F87A15D11444A3EB00318955 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F87A15D01444A3EB00318955 /* CoreLocation.framework */; };
F87A15DD1444A86600318955 /* placeholder-stamp.png in Resources */ = {isa = PBXBuildFile; fileRef = F87A15DB1444A86600318955 /* placeholder-stamp.png */; };
F897DE78142CFEDC000DDD35 /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F897DE79142CFEDC000DDD35 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE6C142CFEDC000DDD35 /* AFHTTPRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F897DE7A142CFEDC000DDD35 /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE6E142CFEDC000DDD35 /* AFImageCache.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F897DE7B142CFEDC000DDD35 /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F897DE7C142CFEDC000DDD35 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F8A27AC7142CFE1300F5E0D6 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27AB2142CFE1300F5E0D6 /* AppDelegate.m */; };
F8A27AC8142CFE1300F5E0D6 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27AB3142CFE1300F5E0D6 /* main.m */; };
F8A27AC9142CFE1300F5E0D6 /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = F8A27AB9142CFE1300F5E0D6 /* Credits.rtf */; };
F8A27ACA142CFE1300F5E0D6 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8A27ABB142CFE1300F5E0D6 /* MainMenu.xib */; };
F8A27ACB142CFE1300F5E0D6 /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27AC0142CFE1300F5E0D6 /* JSONKit.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
F87A159D1444926300318955 /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLConnectionOperation.h; sourceTree = "<group>"; };
F87A159E1444926300318955 /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLConnectionOperation.m; sourceTree = "<group>"; };
F87A15A01444926900318955 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFXMLRequestOperation.h; sourceTree = "<group>"; };
F87A15A11444926900318955 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = "<group>"; };
F87A15A31444927300318955 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFPropertyListRequestOperation.h; sourceTree = "<group>"; };
F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
F87A15C51444A30800318955 /* AFGowallaAPIClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFGowallaAPIClient.h; sourceTree = "<group>"; };
F87A15C61444A30800318955 /* AFGowallaAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFGowallaAPIClient.m; sourceTree = "<group>"; };
F87A15C81444A30800318955 /* NearbySpotsController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NearbySpotsController.h; sourceTree = "<group>"; };
F87A15C91444A30800318955 /* NearbySpotsController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NearbySpotsController.m; sourceTree = "<group>"; };
F87A15CB1444A30800318955 /* Spot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Spot.h; sourceTree = "<group>"; };
F87A15CC1444A30800318955 /* Spot.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Spot.m; sourceTree = "<group>"; };
F87A15D01444A3EB00318955 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; };
F87A15DB1444A86600318955 /* placeholder-stamp.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "placeholder-stamp.png"; sourceTree = "<group>"; };
F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPClient.h; sourceTree = "<group>"; };
F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClient.m; sourceTree = "<group>"; };
F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperation.h; sourceTree = "<group>"; };
F897DE6C142CFEDC000DDD35 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperation.m; sourceTree = "<group>"; };
F897DE6D142CFEDC000DDD35 /* AFImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageCache.h; sourceTree = "<group>"; };
F897DE6E142CFEDC000DDD35 /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageCache.m; sourceTree = "<group>"; };
F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageRequestOperation.h; sourceTree = "<group>"; };
F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperation.m; sourceTree = "<group>"; };
F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFJSONRequestOperation.h; sourceTree = "<group>"; };
F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperation.m; sourceTree = "<group>"; };
F897DE75142CFEDC000DDD35 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = "<group>"; };
F8A27AB1142CFE1300F5E0D6 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
F8A27AB2142CFE1300F5E0D6 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
F8A27AB3142CFE1300F5E0D6 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
F8A27ABA142CFE1300F5E0D6 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = en; path = Credits.rtf; sourceTree = "<group>"; };
F8A27ABC142CFE1300F5E0D6 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = MainMenu.xib; sourceTree = "<group>"; };
F8A27ABF142CFE1300F5E0D6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = "<group>"; };
F8A27AC0142CFE1300F5E0D6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = "<group>"; };
F8A27AC4142CFE1300F5E0D6 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = "<group>"; };
F8A27AC5142CFE1300F5E0D6 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
F8CEEB6A142CEC6E00247B03 /* AFNetworking Mac Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AFNetworking Mac Example.app"; sourceTree = BUILT_PRODUCTS_DIR; };
F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; };
F8CEEB71142CEC6E00247B03 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; };
F8CEEB72142CEC6E00247B03 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; };
F8CEEB73142CEC6E00247B03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
F8CEEB67142CEC6E00247B03 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F87A15D11444A3EB00318955 /* CoreLocation.framework in Frameworks */,
F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
F87A15C41444A30800318955 /* Classes */ = {
isa = PBXGroup;
children = (
F87A15C51444A30800318955 /* AFGowallaAPIClient.h */,
F87A15C61444A30800318955 /* AFGowallaAPIClient.m */,
F87A15C71444A30800318955 /* Controllers */,
F87A15CA1444A30800318955 /* Models */,
);
path = Classes;
sourceTree = "<group>";
};
F87A15C71444A30800318955 /* Controllers */ = {
isa = PBXGroup;
children = (
F87A15C81444A30800318955 /* NearbySpotsController.h */,
F87A15C91444A30800318955 /* NearbySpotsController.m */,
);
path = Controllers;
sourceTree = "<group>";
};
F87A15CA1444A30800318955 /* Models */ = {
isa = PBXGroup;
children = (
F87A15CB1444A30800318955 /* Spot.h */,
F87A15CC1444A30800318955 /* Spot.m */,
);
path = Models;
sourceTree = "<group>";
};
F87A15DA1444A86600318955 /* Images */ = {
isa = PBXGroup;
children = (
F87A15DB1444A86600318955 /* placeholder-stamp.png */,
);
path = Images;
sourceTree = "<group>";
};
F897DE68142CFEDC000DDD35 /* AFNetworking */ = {
isa = PBXGroup;
children = (
F897DE75142CFEDC000DDD35 /* AFNetworking.h */,
F87A159D1444926300318955 /* AFURLConnectionOperation.h */,
F87A159E1444926300318955 /* AFURLConnectionOperation.m */,
F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */,
F897DE6C142CFEDC000DDD35 /* AFHTTPRequestOperation.m */,
F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */,
F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */,
F87A15A01444926900318955 /* AFXMLRequestOperation.h */,
F87A15A11444926900318955 /* AFXMLRequestOperation.m */,
F87A15A31444927300318955 /* AFPropertyListRequestOperation.h */,
F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */,
F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */,
F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */,
F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */,
F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */,
F897DE6D142CFEDC000DDD35 /* AFImageCache.h */,
F897DE6E142CFEDC000DDD35 /* AFImageCache.m */,
);
name = AFNetworking;
path = ../../AFNetworking;
sourceTree = "<group>";
};
F8A27ABD142CFE1300F5E0D6 /* Vendor */ = {
isa = PBXGroup;
children = (
F897DE68142CFEDC000DDD35 /* AFNetworking */,
F8A27ABE142CFE1300F5E0D6 /* JSONKit */,
);
path = Vendor;
sourceTree = "<group>";
};
F8A27ABE142CFE1300F5E0D6 /* JSONKit */ = {
isa = PBXGroup;
children = (
F8A27ABF142CFE1300F5E0D6 /* JSONKit.h */,
F8A27AC0142CFE1300F5E0D6 /* JSONKit.m */,
);
path = JSONKit;
sourceTree = "<group>";
};
F8A27ACD142CFE3000F5E0D6 /* Supporting Files */ = {
isa = PBXGroup;
children = (
F8A27AB3142CFE1300F5E0D6 /* main.m */,
F8A27AB1142CFE1300F5E0D6 /* Info.plist */,
F8A27AB2142CFE1300F5E0D6 /* AppDelegate.m */,
F8A27AC4142CFE1300F5E0D6 /* Prefix.pch */,
F8A27AC5142CFE1300F5E0D6 /* AppDelegate.h */,
F8A27AB9142CFE1300F5E0D6 /* Credits.rtf */,
F8A27ABB142CFE1300F5E0D6 /* MainMenu.xib */,
F87A15DA1444A86600318955 /* Images */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
F8CEEB5F142CEC6E00247B03 = {
isa = PBXGroup;
children = (
F87A15C41444A30800318955 /* Classes */,
F8A27ACD142CFE3000F5E0D6 /* Supporting Files */,
F8A27ABD142CFE1300F5E0D6 /* Vendor */,
F8CEEB6D142CEC6E00247B03 /* Frameworks */,
F8CEEB6B142CEC6E00247B03 /* Products */,
);
sourceTree = "<group>";
};
F8CEEB6B142CEC6E00247B03 /* Products */ = {
isa = PBXGroup;
children = (
F8CEEB6A142CEC6E00247B03 /* AFNetworking Mac Example.app */,
);
name = Products;
sourceTree = "<group>";
};
F8CEEB6D142CEC6E00247B03 /* Frameworks */ = {
isa = PBXGroup;
children = (
F87A15D01444A3EB00318955 /* CoreLocation.framework */,
F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */,
F8CEEB70142CEC6E00247B03 /* Other Frameworks */,
);
name = Frameworks;
sourceTree = "<group>";
};
F8CEEB70142CEC6E00247B03 /* Other Frameworks */ = {
isa = PBXGroup;
children = (
F8CEEB71142CEC6E00247B03 /* AppKit.framework */,
F8CEEB72142CEC6E00247B03 /* CoreData.framework */,
F8CEEB73142CEC6E00247B03 /* Foundation.framework */,
);
name = "Other Frameworks";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
F8CEEB69142CEC6E00247B03 /* AFNetworking Mac Example */ = {
isa = PBXNativeTarget;
buildConfigurationList = F8CEEB88142CEC6E00247B03 /* Build configuration list for PBXNativeTarget "AFNetworking Mac Example" */;
buildPhases = (
F8CEEB66142CEC6E00247B03 /* Sources */,
F8CEEB67142CEC6E00247B03 /* Frameworks */,
F8CEEB68142CEC6E00247B03 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = "AFNetworking Mac Example";
productName = "AFNetworking Mac Example";
productReference = F8CEEB6A142CEC6E00247B03 /* AFNetworking Mac Example.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
F8CEEB61142CEC6E00247B03 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0420;
ORGANIZATIONNAME = Gowalla;
};
buildConfigurationList = F8CEEB64142CEC6E00247B03 /* Build configuration list for PBXProject "AFNetworking Mac Example" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = F8CEEB5F142CEC6E00247B03;
productRefGroup = F8CEEB6B142CEC6E00247B03 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
F8CEEB69142CEC6E00247B03 /* AFNetworking Mac Example */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
F8CEEB68142CEC6E00247B03 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
F8A27AC9142CFE1300F5E0D6 /* Credits.rtf in Resources */,
F8A27ACA142CFE1300F5E0D6 /* MainMenu.xib in Resources */,
F87A15DD1444A86600318955 /* placeholder-stamp.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
F8CEEB66142CEC6E00247B03 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
F8A27AC7142CFE1300F5E0D6 /* AppDelegate.m in Sources */,
F8A27AC8142CFE1300F5E0D6 /* main.m in Sources */,
F8A27ACB142CFE1300F5E0D6 /* JSONKit.m in Sources */,
F897DE78142CFEDC000DDD35 /* AFHTTPClient.m in Sources */,
F897DE79142CFEDC000DDD35 /* AFHTTPRequestOperation.m in Sources */,
F897DE7A142CFEDC000DDD35 /* AFImageCache.m in Sources */,
F897DE7B142CFEDC000DDD35 /* AFImageRequestOperation.m in Sources */,
F897DE7C142CFEDC000DDD35 /* AFJSONRequestOperation.m in Sources */,
F87A159F1444926300318955 /* AFURLConnectionOperation.m in Sources */,
F87A15A21444926A00318955 /* AFXMLRequestOperation.m in Sources */,
F87A15A51444927300318955 /* AFPropertyListRequestOperation.m in Sources */,
F87A15CD1444A30800318955 /* AFGowallaAPIClient.m in Sources */,
F87A15CE1444A30800318955 /* NearbySpotsController.m in Sources */,
F87A15CF1444A30800318955 /* Spot.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
F8A27AB9142CFE1300F5E0D6 /* Credits.rtf */ = {
isa = PBXVariantGroup;
children = (
F8A27ABA142CFE1300F5E0D6 /* en */,
);
name = Credits.rtf;
path = en.lproj;
sourceTree = "<group>";
};
F8A27ABB142CFE1300F5E0D6 /* MainMenu.xib */ = {
isa = PBXVariantGroup;
children = (
F8A27ABC142CFE1300F5E0D6 /* en */,
);
name = MainMenu.xib;
path = en.lproj;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
F8CEEB86142CEC6E00247B03 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_64_BIT)";
CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.6;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
};
name = Debug;
};
F8CEEB87142CEC6E00247B03 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_64_BIT)";
CLANG_ENABLE_OBJC_ARC = YES;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.6;
SDKROOT = macosx;
};
name = Release;
};
F8CEEB89142CEC6E00247B03 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = Prefix.pch;
INFOPLIST_FILE = Info.plist;
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
name = Debug;
};
F8CEEB8A142CEC6E00247B03 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = Prefix.pch;
INFOPLIST_FILE = Info.plist;
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
F8CEEB64142CEC6E00247B03 /* Build configuration list for PBXProject "AFNetworking Mac Example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F8CEEB86142CEC6E00247B03 /* Debug */,
F8CEEB87142CEC6E00247B03 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
F8CEEB88142CEC6E00247B03 /* Build configuration list for PBXNativeTarget "AFNetworking Mac Example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F8CEEB89142CEC6E00247B03 /* Debug */,
F8CEEB8A142CEC6E00247B03 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = F8CEEB61142CEC6E00247B03 /* Project object */;
}

View file

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8CEEB69142CEC6E00247B03"
BuildableName = "AFNetworking Mac Example.app"
BlueprintName = "AFNetworking Mac Example"
ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8CEEB69142CEC6E00247B03"
BuildableName = "AFNetworking Mac Example.app"
BlueprintName = "AFNetworking Mac Example"
ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8CEEB69142CEC6E00247B03"
BuildableName = "AFNetworking Mac Example.app"
BlueprintName = "AFNetworking Mac Example"
ReferencedContainer = "container:AFNetworking Mac Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View file

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>AFNetworking Mac Example.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>F8CEEB69142CEC6E00247B03</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>

32
Mac Example/AppDelegate.h Normal file
View file

@ -0,0 +1,32 @@
// AppDelegate.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 <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *_window;
}
@property (strong) IBOutlet NSWindow *window;
@end

33
Mac Example/AppDelegate.m Normal file
View file

@ -0,0 +1,33 @@
// AppDelegate.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 "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
}
@end

View file

@ -0,0 +1,64 @@
// AFGowallaAPI.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 "AFGowallaAPIClient.h"
#import "AFJSONRequestOperation.h"
// Replace this with your own API Key, available at http://api.gowalla.com/api/keys/
NSString * const kAFGowallaClientID = @"e7ccb7d3d2414eb2af4663fc91eb2793";
NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/";
@implementation AFGowallaAPIClient
+ (AFGowallaAPIClient *)sharedClient {
static AFGowallaAPIClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:kAFGowallaBaseURLString]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
// X-Gowalla-API-Key HTTP Header; see http://api.gowalla.com/api/docs
[self setDefaultHeader:@"X-Gowalla-API-Key" value:kAFGowallaClientID];
// X-Gowalla-API-Version HTTP Header; see http://api.gowalla.com/api/docs
[self setDefaultHeader:@"X-Gowalla-API-Version" value:@"1"];
return self;
}
@end

View file

@ -0,0 +1,30 @@
// NearbySpotsViewController.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 <Cocoa/Cocoa.h>
#import <CoreLocation/CoreLocation.h>
@interface NearbySpotsController : NSObject <CLLocationManagerDelegate, NSTableViewDataSource, NSTableViewDelegate>
@property (strong) IBOutlet NSTableView *tableView;
@end

View file

@ -0,0 +1,124 @@
// NearbySpotsViewController.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 "NearbySpotsController.h"
#import "Spot.h"
#import "AFImageRequestOperation.h"
#import "AFImageCache.h"
@interface NearbySpotsController ()
@property (strong) NSArray *nearbySpots;
@property (strong) CLLocationManager *locationManager;
@property (strong) NSOperationQueue *imageOperationQueue;
- (void)loadSpotsForLocation:(CLLocation *)location;
@end
@implementation NearbySpotsController
@synthesize nearbySpots = _nearbySpots;
@synthesize locationManager = _locationManager;
@synthesize imageOperationQueue = _imageOperationQueue;
@synthesize tableView = _tableView;
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.nearbySpots = [NSArray array];
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = 80.0;
self.imageOperationQueue = [[NSOperationQueue alloc] init];
self.imageOperationQueue.maxConcurrentOperationCount = 8;
return self;
}
- (void)awakeFromNib {
// Load from a fixed location, in case location services are disabled or unavailable
CLLocation *austin = [[CLLocation alloc] initWithLatitude:30.2669444 longitude:-97.7427778];
[self loadSpotsForLocation:austin];
[self.locationManager startUpdatingLocation];
}
- (void)loadSpotsForLocation:(CLLocation *)location {
[Spot spotsWithURLString:@"/spots" near:location parameters:[NSDictionary dictionaryWithObject:@"128" forKey:@"per_page"] block:^(NSArray *records) {
self.nearbySpots = [records sortedArrayUsingComparator:^ NSComparisonResult(id obj1, id obj2) {
CLLocationDistance d1 = [[(Spot *)obj1 location] distanceFromLocation:location];
CLLocationDistance d2 = [[(Spot *)obj2 location] distanceFromLocation:location];
if (d1 < d2) {
return NSOrderedAscending;
} else if (d1 > d2) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
[self.tableView reloadData];
}];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self loadSpotsForLocation:newLocation];
}
#pragma mark - NSTableViewDataSource
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [self.nearbySpots count];
}
// The following is what happens when a longtime iOS dev attempts to work with AppKit. I'm sure there's a _much_ better way to do this.
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
Spot *spot = [self.nearbySpots objectAtIndex:row];
if ([[tableColumn dataCell] isMemberOfClass:[NSImageCell class]]) {
NSURL *imageURL = [NSURL URLWithString:spot.imageURLString];
NSImage *image = [[AFImageCache sharedImageCache] cachedImageForURL:imageURL cacheName:nil];
if (!image) {
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:spot.imageURLString]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:imageRequest success:^(NSImage *image) {
[tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:row] columnIndexes:[NSIndexSet indexSetWithIndex:0]];
}];
[self.imageOperationQueue addOperation:operation];
image = [NSImage imageNamed:@"placeholder-stamp.png"];
}
return image;
} else {
return spot.name;
}
}
@end

View file

@ -0,0 +1,43 @@
// Spot.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface Spot : NSObject {
@private
NSString *_name;
NSString *_imageURLString;
NSNumber *_latitude;
NSNumber *_longitude;
}
@property (strong) NSString *name;
@property (strong) NSString *imageURLString;
@property (strong) NSNumber *latitude;
@property (strong) NSNumber *longitude;
@property (readonly) CLLocation *location;
- (id)initWithAttributes:(NSDictionary *)attributes;
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(void (^)(NSArray *records))block;
@end

View file

@ -0,0 +1,76 @@
// Spot.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 "Spot.h"
#import "AFGowallaAPIClient.h"
@implementation Spot
@synthesize name = _name;
@synthesize imageURLString = _imageURLString;
@synthesize latitude = _latitude;
@synthesize longitude = _longitude;
@dynamic location;
- (id)initWithAttributes:(NSDictionary *)attributes {
self = [super init];
if (!self) {
return nil;
}
self.name = [attributes valueForKeyPath:@"name"];
self.imageURLString = [attributes valueForKeyPath:@"image_url"];
self.latitude = [attributes valueForKeyPath:@"lat"];
self.longitude = [attributes valueForKeyPath:@"lng"];
return self;
}
- (CLLocation *)location {
return [[CLLocation alloc] initWithLatitude:[self.latitude doubleValue] longitude:[self.longitude doubleValue]];
}
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(void (^)(NSArray *records))block {
NSDictionary *mutableParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
if (location) {
[mutableParameters setValue:[NSString stringWithFormat:@"%1.7f", location.coordinate.latitude] forKey:@"lat"];
[mutableParameters setValue:[NSString stringWithFormat:@"%1.7f", location.coordinate.longitude] forKey:@"lng"];
}
[[AFGowallaAPIClient sharedClient] getPath:urlString parameters:mutableParameters success:^(id object) {
NSMutableArray *mutableRecords = [NSMutableArray array];
for (NSDictionary *attributes in [object valueForKeyPath:@"spots"]) {
Spot *spot = [[Spot alloc] initWithAttributes:attributes];
[mutableRecords addObject:spot];
}
if (block) {
block([NSArray arrayWithArray:mutableRecords]);
}
} failure:^(NSHTTPURLResponse *response, NSError *error) {
if (block) {
block([NSArray array]);
}
}];
}
@end

View file

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

36
Mac Example/Info.plist Normal file
View file

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.alamofire.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.utilities</string>
<key>LSMinimumSystemVersion</key>
<string>${MACOSX_DEPLOYMENT_TARGET}</string>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2011 Gowalla. All rights reserved.</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>

7
Mac Example/Prefix.pch Normal file
View file

@ -0,0 +1,7 @@
//
// Prefix header for all source files of the 'AFNetworking Mac Example' target in the 'AFNetworking Mac Example' project
//
#ifdef __OBJC__
#import <Cocoa/Cocoa.h>
#endif

View file

@ -0,0 +1,13 @@
{\rtf1\ansi\ansicpg1252\cocoartf1138
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\listtable{\list\listtemplateid1\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace360\levelindent0{\*\levelmarker \{hyphen\}}{\leveltext\leveltemplateid1\'01\uc0\u8259 ;}{\levelnumbers;}\fi-360\li720\lin720 }{\listname ;}\listid1}}
{\*\listoverridetable{\listoverride\listid1\listoverridecount0\ls1}}
\vieww9600\viewh8400\viewkind0
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720
\f0\b\fs24 \cf0 AFNetworking Creators\
\pard\tx220\tx720\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\li720\fi-720\pardirnatural
\ls1\ilvl0
\b0 \cf0 {\listtext \uc0\u8259 }Mattt Thompson\
{\listtext \uc0\u8259 }Scott Raymond}

File diff suppressed because it is too large Load diff

29
Mac Example/main.m Normal file
View file

@ -0,0 +1,29 @@
// main.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 <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}

View file

@ -1,16 +1,8 @@
# AFNetworking
## A delightful iOS networking library with NSOperations and block-based callbacks
## A delightful iOS and OS X networking framework
### There's a lot to be said for a networking library that you can wrap your head around. API design matters, too. Code at its best is poetry, and should be designed to delight (but never surprise).
AFNetworking is lovingly crafted to make best use of our favorite parts of Apple's `Foundation` framework: `NSOperation` for managing multiple concurrent requests, `NSURLRequest` & `NSHTTPURLResponse` to encapsulate state, `NSCache` & `NSURLCache` for performant and compliant cacheing behavior, and blocks to keep request / response handling code in a single logical unit in code.
At its core is `AFHTTPRequestOperation`, a thin wrapper around `NSURLConnection`, which provides a block callback for when the operation completes. Everything else is built on top of that in a way that's completely modular: take what you need, leave what you don't.
If you're tired of massive libraries that try to do too much...
If you've taken it upon yourself to roll your own hacky solution...
If you want a library that _actually makes iOS networking code kinda fun_...
...try out AFNetworking
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of familiar Foundation network classes, using `NSOperation` for scheduling and concurrency, and blocks for convenience and flexibility. It's designed to make common tasks easy, and to make complex tasks simple.
## Documentation
@ -18,15 +10,32 @@ Online documentation is available at http://gowalla.github.com/AFNetworking/.
To install the docset directly into your local Xcode organizer, first [install `appledoc`](https://github.com/tomaz/appledoc), and then clone this project and run `appledoc -p AFNetworking -c "Gowalla" --company-id com.gowalla AFNetworking/*.h`
## Example Projects
Be sure to download and run the example projects for iOS and Mac. Both example projects serve as models of how one might integrate AFNetworking into their own project.
## Example Usage
### JSON Request
``` objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://gowalla.com/users/mattt.json"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:request success:^(id JSON) {
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Name: %@ %@", [JSON valueForKeyPath:@"first_name"], [JSON valueForKeyPath:@"last_name"]);
}];
} failure:nil];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
```
### XML Request
``` objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]];
AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = self;
[XMLParser parse];
} failure:nil];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
@ -36,7 +45,7 @@ NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
``` objective-c
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
```
### API Client Request
@ -54,7 +63,7 @@ UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0
``` objective-c
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [[AFHTTPClient sharedClient] multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:data name:@"avatar"];
[formData appendPartWithFileData:data mimeType:@"image/jpeg" name:@"avatar"];
}];
AFHTTPRequestOperation *operation = [AFHTTPRequestOperation operationWithRequest:request completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) {
@ -75,17 +84,14 @@ NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://gowalla.com/friendships/request?user_id=1699"]];
[request setHTTPMethod:@"POST"];
NSDictionary *headers = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Token token=\"%@\"", kOAuthToken] forKey:@"Authorization"];
[request setAllHTTPHeaderFields:headers];
AFHTTPRequestOperation *operation = [AFHTTPRequestOperation operationWithRequest:request completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) {
BOOL HTTPStatusCodeIsAcceptable = [[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)] containsIndex:[response statusCode]];
if (HTTPStatusCodeIsAcceptable) {
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
operation.completionBlock = ^ {
if ([operation hasAcceptableStatusCode]) {
NSLog(@"Friend Request Sent");
} else {
NSLog(@"[Error]: (%@ %@) %@", [request HTTPMethod], [[request URL] relativePath], error);
NSLog(@"[Error]: (%@ %@) %@", [operation.request HTTPMethod], [[operation.request URL] relativePath], operation.error);
}
}];
};
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
@ -95,31 +101,28 @@ NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
``` objective-c
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
NSOutputStream *outputStream = [NSOutputStream outputStreamToMemory];
AFHTTPRequestOperation *operation = [AFHTTPRequestOperation streamingOperationWithRequest:request inputStream:inputStream outputStream:outputStream completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Streaming operation complete");
}];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
```
## Example Project
## Requirements
In order to demonstrate the power and flexibility of AFNetworking, we've included a small sample project, which asks for your current location and displays [Gowalla](http://gowalla.com/) spots nearby you. It uses `AFJSONRequestOperation` to load and parse the spots JSON, and a category on `UIImageView` to asynchronously load spot stamp images as you scroll.
## Dependencies
* [iOS 4.0+](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html%23//apple_ref/doc/uid/TP40009559-SW1) - AFNetworking uses blocks, which were introduced in iOS 4.
* If you're using iOS 5, AFJSONRequestOperation uses JSON will use the built-in NSJSONSerialization class to parse JSON responses. If this is not available, it falls back on [JSONKit](https://github.com/johnezang/JSONKit).
AFNetworking requires either [iOS 4.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html%23//apple_ref/doc/uid/TP40009559-SW1) and above, or [Mac OS 10.6](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) and above.
### ARC Support
If you are including AFNetworking in a project with [Automatic Reference Counting (ARC)](http://clang.llvm.org/docs/AutomaticReferenceCounting.html) enabled, you will need to set the `-fno-objc-arc` compiler flag on all of the AFNetworking source files. To do this in Xcode, go to your active target and select the "Build Phases" tab. In the "Compiler Flags" column, set `-fno-objc-arc` for each of the AFNetworking source files.
If you are including AFNetworking in a project that uses [Automatic Reference Counting (ARC)](http://clang.llvm.org/docs/AutomaticReferenceCounting.html) enabled, you will need to set the `-fno-objc-arc` compiler flag on all of the AFNetworking source files. To do this in Xcode, go to your active target and select the "Build Phases" tab. In the "Compiler Flags" column, set `-fno-objc-arc` for each of the AFNetworking source files.
This is certainly suboptimal, forking the project into an ARC and non-ARC branch would be extremely difficult to maintain. On the bright side, we're very excited about [CocoaPods](https://github.com/alloy/cocoapods), which is a promising solution to this and many other pain points.
Although this is suboptimal, forking the project into an ARC and non-ARC branch would be extremely difficult to maintain. On the bright side, we're very excited about [CocoaPods](https://github.com/alloy/cocoapods) as a potential solution.
### Mac OS X Support
## Dependencies
Full support for OS X is planned for the very near future. In the meantime, you are perfectly safe to use `AFHTTPRequestOperation`, `AFJSONRequestOperation`, `AFHTTPClient`, and `AFNetworkActivityIndicatorManager`.
* [JSONKit](https://github.com/johnezang/JSONKit)
## Credits

View file

@ -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 */; };
@ -29,10 +30,14 @@
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 */; };
F8F4B17F143E07030064C9E6 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */; };
F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FBFA97142AA238001409DB /* AFHTTPClient.m */; };
/* 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 = "<group>"; };
F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = "<group>"; };
F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = "<group>"; };
F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = "<group>"; };
F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = "<group>"; };
@ -53,6 +58,7 @@
F8D25D181396A9D300CF3BD6 /* placeholder-stamp@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "placeholder-stamp@2x.png"; path = "Images/placeholder-stamp@2x.png"; sourceTree = SOURCE_ROOT; };
F8D25D1B1396A9DE00CF3BD6 /* AFGowallaAPIClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFGowallaAPIClient.h; path = Classes/AFGowallaAPIClient.h; sourceTree = "<group>"; };
F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFGowallaAPIClient.m; path = Classes/AFGowallaAPIClient.m; sourceTree = "<group>"; };
F8D7DE781445F354000EF2F3 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../AFNetworking/AFNetworking.h; sourceTree = "<group>"; };
F8DA09C71396AB690057D0CC /* NearbySpotsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NearbySpotsViewController.h; sourceTree = "<group>"; };
F8DA09C81396AB690057D0CC /* NearbySpotsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NearbySpotsViewController.m; sourceTree = "<group>"; };
F8DA09CA1396AB690057D0CC /* Spot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Spot.h; sourceTree = "<group>"; };
@ -63,7 +69,7 @@
F8DA09E51396AC220057D0CC /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = SOURCE_ROOT; };
F8DA09E61396AC220057D0CC /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = SOURCE_ROOT; };
F8DA09E71396AC220057D0CC /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = SOURCE_ROOT; };
F8E469601395739C00DB05C8 /* AFNetworkingExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AFNetworkingExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AFNetworking iOS Example.app"; sourceTree = BUILT_PRODUCTS_DIR; };
F8E469641395739D00DB05C8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
F8E469661395739D00DB05C8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
F8E469681395739D00DB05C8 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
@ -71,6 +77,10 @@
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 = "<group>"; };
F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = "<group>"; };
F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFXMLRequestOperation.h; path = ../AFNetworking/AFXMLRequestOperation.h; sourceTree = "<group>"; };
F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFXMLRequestOperation.m; path = ../AFNetworking/AFXMLRequestOperation.m; sourceTree = "<group>"; };
F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = "<group>"; };
F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
@ -92,15 +102,6 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
F85CE2D613EC47BC00BFAE01 /* Categories */ = {
isa = PBXGroup;
children = (
F874B5D813E0AA6500B28E3E /* UIImageView+AFNetworking.h */,
F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */,
);
name = Categories;
sourceTree = "<group>";
};
F8D25D0F1396A9C400CF3BD6 /* JSONKit */ = {
isa = PBXGroup;
children = (
@ -166,7 +167,7 @@
F8E469611395739C00DB05C8 /* Products */ = {
isa = PBXGroup;
children = (
F8E469601395739C00DB05C8 /* AFNetworkingExample.app */,
F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */,
);
name = Products;
sourceTree = "<group>";
@ -221,19 +222,27 @@
F8E469941395744600DB05C8 /* AFNetworking */ = {
isa = PBXGroup;
children = (
F8D7DE781445F354000EF2F3 /* AFNetworking.h */,
F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */,
F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */,
F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */,
F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */,
F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */,
F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */,
F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */,
F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */,
F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */,
F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */,
F8FBFA96142AA237001409DB /* AFHTTPClient.h */,
F8FBFA97142AA238001409DB /* AFHTTPClient.m */,
F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */,
F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */,
F874B5D213E0AA6500B28E3E /* AFImageCache.h */,
F874B5CA13E0AA6500B28E3E /* AFImageCache.m */,
F874B5D813E0AA6500B28E3E /* UIImageView+AFNetworking.h */,
F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */,
F874B5D513E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.h */,
F874B5CD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m */,
F85CE2D613EC47BC00BFAE01 /* Categories */,
);
name = AFNetworking;
sourceTree = "<group>";
@ -260,9 +269,9 @@
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
F8E4695F1395739C00DB05C8 /* AFNetworkingExample */ = {
F8E4695F1395739C00DB05C8 /* AFNetworking iOS Example */ = {
isa = PBXNativeTarget;
buildConfigurationList = F8E469811395739D00DB05C8 /* Build configuration list for PBXNativeTarget "AFNetworkingExample" */;
buildConfigurationList = F8E469811395739D00DB05C8 /* Build configuration list for PBXNativeTarget "AFNetworking iOS Example" */;
buildPhases = (
F8E4695C1395739C00DB05C8 /* Sources */,
F8E4695D1395739C00DB05C8 /* Frameworks */,
@ -272,9 +281,9 @@
);
dependencies = (
);
name = AFNetworkingExample;
name = "AFNetworking iOS Example";
productName = AFNetworkingExample;
productReference = F8E469601395739C00DB05C8 /* AFNetworkingExample.app */;
productReference = F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
@ -286,7 +295,7 @@
LastUpgradeCheck = 0420;
ORGANIZATIONNAME = Gowalla;
};
buildConfigurationList = F8E4695A1395739C00DB05C8 /* Build configuration list for PBXProject "AFNetworking Example" */;
buildConfigurationList = F8E4695A1395739C00DB05C8 /* Build configuration list for PBXProject "AFNetworking iOS Example" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
@ -298,7 +307,7 @@
projectDirPath = "";
projectRoot = "";
targets = (
F8E4695F1395739C00DB05C8 /* AFNetworkingExample */,
F8E4695F1395739C00DB05C8 /* AFNetworking iOS Example */,
);
};
/* End PBXProject section */
@ -335,6 +344,9 @@
F874B5DD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m in Sources */,
F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */,
F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */,
F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */,
F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */,
F8F4B17F143E07030064C9E6 /* AFXMLRequestOperation.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@ -410,7 +422,7 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
F8E4695A1395739C00DB05C8 /* Build configuration list for PBXProject "AFNetworking Example" */ = {
F8E4695A1395739C00DB05C8 /* Build configuration list for PBXProject "AFNetworking iOS Example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F8E4697F1395739D00DB05C8 /* Debug */,
@ -419,7 +431,7 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
F8E469811395739D00DB05C8 /* Build configuration list for PBXNativeTarget "AFNetworkingExample" */ = {
F8E469811395739D00DB05C8 /* Build configuration list for PBXNativeTarget "AFNetworking iOS Example" */ = {
isa = XCConfigurationList;
buildConfigurations = (
F8E469821395739D00DB05C8 /* Debug */,

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
version = "1.8">
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
@ -14,9 +14,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
BuildableName = "AFNetworkingExample.app"
BlueprintName = "AFNetworkingExample"
ReferencedContainer = "container:AFNetworking Example.xcodeproj">
BuildableName = "AFNetworking iOS Example.app"
BlueprintName = "AFNetworking iOS Example"
ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
@ -32,8 +32,6 @@
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
displayScaleIsEnabled = "NO"
displayScale = "1.00"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
@ -43,22 +41,15 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
BuildableName = "AFNetworkingExample.app"
BlueprintName = "AFNetworkingExample"
ReferencedContainer = "container:AFNetworking Example.xcodeproj">
BuildableName = "AFNetworking iOS Example.app"
BlueprintName = "AFNetworking iOS Example"
ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
<AdditionalOption
key = "NSZombieEnabled"
value = "YES"
isEnabled = "YES">
</AdditionalOption>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
displayScaleIsEnabled = "NO"
displayScale = "1.00"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
@ -68,9 +59,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "F8E4695F1395739C00DB05C8"
BuildableName = "AFNetworkingExample.app"
BlueprintName = "AFNetworkingExample"
ReferencedContainer = "container:AFNetworking Example.xcodeproj">
BuildableName = "AFNetworking iOS Example.app"
BlueprintName = "AFNetworking iOS Example"
ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>

View file

@ -4,10 +4,10 @@
<dict>
<key>SchemeUserState</key>
<dict>
<key>AFNetworking Example.xcscheme</key>
<key>AFNetworking iOS Example.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>1</integer>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>

View file

@ -0,0 +1,31 @@
// AFGowallaAPI.h
//
// Copyright (c) 2011 Gowalla (http://gowalla.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
extern NSString * const kAFGowallaClientID;
extern NSString * const kAFGowallaBaseURLString;
@interface AFGowallaAPIClient : AFHTTPClient
+ (AFGowallaAPIClient *)sharedClient;
@end

View file

@ -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";
@ -45,6 +47,11 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/";
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:@"Accept" value:@"application/json"];
// X-Gowalla-API-Key HTTP Header; see http://api.gowalla.com/api/docs
[self setDefaultHeader:@"X-Gowalla-API-Key" value:kAFGowallaClientID];

View file

@ -23,8 +23,6 @@
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
typedef void (^AFRecordsBlock)(NSArray *records);
@interface Spot : NSObject {
@private
NSString *_name;
@ -40,6 +38,6 @@ typedef void (^AFRecordsBlock)(NSArray *records);
@property (readonly) CLLocation *location;
- (id)initWithAttributes:(NSDictionary *)attributes;
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(AFRecordsBlock)block;
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(void (^)(NSArray *records))block;
@end

View file

@ -57,7 +57,7 @@
return [[[CLLocation alloc] initWithLatitude:[self.latitude doubleValue] longitude:[self.longitude doubleValue]] autorelease];
}
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(AFRecordsBlock)block {
+ (void)spotsWithURLString:(NSString *)urlString near:(CLLocation *)location parameters:(NSDictionary *)parameters block:(void (^)(NSArray *records))block {
NSDictionary *mutableParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
if (location) {
[mutableParameters setValue:[NSString stringWithFormat:@"%1.7f", location.coordinate.latitude] forKey:@"lat"];

View file

@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

View file

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

251
iOS Example/Vendor/JSONKit/JSONKit.h vendored Normal file
View file

@ -0,0 +1,251 @@
//
// JSONKit.h
// http://github.com/johnezang/JSONKit
// Dual licensed under either the terms of the BSD License, or alternatively
// under the terms of the Apache License, Version 2.0, as specified below.
//
/*
Copyright (c) 2011, John Engelhart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Zang Industries nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright 2011 John Engelhart
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stddef.h>
#include <stdint.h>
#include <limits.h>
#include <TargetConditionals.h>
#include <AvailabilityMacros.h>
#ifdef __OBJC__
#import <Foundation/NSArray.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSString.h>
#endif // __OBJC__
#ifdef __cplusplus
extern "C" {
#endif
// For Mac OS X < 10.5.
#ifndef NSINTEGER_DEFINED
#define NSINTEGER_DEFINED
#if defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
typedef long NSInteger;
typedef unsigned long NSUInteger;
#define NSIntegerMin LONG_MIN
#define NSIntegerMax LONG_MAX
#define NSUIntegerMax ULONG_MAX
#else // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
typedef int NSInteger;
typedef unsigned int NSUInteger;
#define NSIntegerMin INT_MIN
#define NSIntegerMax INT_MAX
#define NSUIntegerMax UINT_MAX
#endif // defined(__LP64__) || defined(NS_BUILD_32_LIKE_64)
#endif // NSINTEGER_DEFINED
#ifndef _JSONKIT_H_
#define _JSONKIT_H_
#if defined(__GNUC__) && (__GNUC__ >= 4) && defined(__APPLE_CC__) && (__APPLE_CC__ >= 5465)
#define JK_DEPRECATED_ATTRIBUTE __attribute__((deprecated))
#else
#define JK_DEPRECATED_ATTRIBUTE
#endif
#define JSONKIT_VERSION_MAJOR 1
#define JSONKIT_VERSION_MINOR 4
typedef NSUInteger JKFlags;
/*
JKParseOptionComments : Allow C style // and /_* ... *_/ (without a _, obviously) comments in JSON.
JKParseOptionUnicodeNewlines : Allow Unicode recommended (?:\r\n|[\n\v\f\r\x85\p{Zl}\p{Zp}]) newlines.
JKParseOptionLooseUnicode : Normally the decoder will stop with an error at any malformed Unicode.
This option allows JSON with malformed Unicode to be parsed without reporting an error.
Any malformed Unicode is replaced with \uFFFD, or "REPLACEMENT CHARACTER".
*/
enum {
JKParseOptionNone = 0,
JKParseOptionStrict = 0,
JKParseOptionComments = (1 << 0),
JKParseOptionUnicodeNewlines = (1 << 1),
JKParseOptionLooseUnicode = (1 << 2),
JKParseOptionPermitTextAfterValidJSON = (1 << 3),
JKParseOptionValidFlags = (JKParseOptionComments | JKParseOptionUnicodeNewlines | JKParseOptionLooseUnicode | JKParseOptionPermitTextAfterValidJSON),
};
typedef JKFlags JKParseOptionFlags;
enum {
JKSerializeOptionNone = 0,
JKSerializeOptionPretty = (1 << 0),
JKSerializeOptionEscapeUnicode = (1 << 1),
JKSerializeOptionEscapeForwardSlashes = (1 << 4),
JKSerializeOptionValidFlags = (JKSerializeOptionPretty | JKSerializeOptionEscapeUnicode | JKSerializeOptionEscapeForwardSlashes),
};
typedef JKFlags JKSerializeOptionFlags;
#ifdef __OBJC__
typedef struct JKParseState JKParseState; // Opaque internal, private type.
// As a general rule of thumb, if you use a method that doesn't accept a JKParseOptionFlags argument, it defaults to JKParseOptionStrict
@interface JSONDecoder : NSObject {
JKParseState *parseState;
}
+ (id)decoder;
+ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (void)clearCache;
// The parse... methods were deprecated in v1.4 in favor of the v1.4 objectWith... methods.
- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
// The NSData MUST be UTF8 encoded JSON.
- (id)parseJSONData:(NSData *)jsonData JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData: instead.
- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error JK_DEPRECATED_ATTRIBUTE; // Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
// Methods that return immutable collection objects.
- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
// The NSData MUST be UTF8 encoded JSON.
- (id)objectWithData:(NSData *)jsonData;
- (id)objectWithData:(NSData *)jsonData error:(NSError **)error;
// Methods that return mutable collection objects.
- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length;
- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error;
// The NSData MUST be UTF8 encoded JSON.
- (id)mutableObjectWithData:(NSData *)jsonData;
- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error;
@end
////////////
#pragma mark Deserializing methods
////////////
@interface NSString (JSONKitDeserializing)
- (id)objectFromJSONString;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
- (id)mutableObjectFromJSONString;
- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
@interface NSData (JSONKitDeserializing)
// The NSData MUST be UTF8 encoded JSON.
- (id)objectFromJSONData;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
- (id)mutableObjectFromJSONData;
- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags;
- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error;
@end
////////////
#pragma mark Serializing methods
////////////
@interface NSString (JSONKitSerializing)
// Convenience methods for those that need to serialize the receiving NSString (i.e., instead of having to serialize a NSArray with a single NSString, you can "serialize to JSON" just the NSString).
// Normally, a string that is serialized to JSON has quotation marks surrounding it, which you may or may not want when serializing a single string, and can be controlled with includeQuotes:
// includeQuotes:YES `a "test"...` -> `"a \"test\"..."`
// includeQuotes:NO `a "test"...` -> `a \"test\"...`
- (NSData *)JSONData; // Invokes JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
- (NSString *)JSONString; // Invokes JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error;
@end
@interface NSArray (JSONKitSerializing)
- (NSData *)JSONData;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (NSString *)JSONString;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
@end
@interface NSDictionary (JSONKitSerializing)
- (NSData *)JSONData;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (NSString *)JSONString;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
@end
#ifdef __BLOCKS__
@interface NSArray (JSONKitSerializingBlockAdditions)
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
@end
@interface NSDictionary (JSONKitSerializingBlockAdditions)
- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error;
@end
#endif
#endif // __OBJC__
#endif // _JSONKIT_H_
#ifdef __cplusplus
} // extern "C"
#endif

3011
iOS Example/Vendor/JSONKit/JSONKit.m vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,83 @@
// TTTLocationFormatter.h
//
// Copyright (c) 2011 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
typedef enum {
TTTNorthDirection,
TTTNortheastDirection,
TTTEastDirection,
TTTSoutheastDirection,
TTTSouthDirection,
TTTSouthwestDirection,
TTTWestDirection,
TTTNorthwestDirection,
} TTTLocationCardinalDirection;
extern TTTLocationCardinalDirection TTTLocationCardinalDirectionFromBearing(CLLocationDegrees bearing);
typedef enum {
TTTCoordinateLatLngOrder = 0,
TTTCoordinateLngLatOrder,
} TTTLocationFormatterCoordinateOrder;
typedef enum {
TTTBearingWordStyle = 0,
TTTBearingAbbreviationWordStyle,
TTTBearingNumericStyle,
} TTTLocationFormatterBearingStyle;
typedef enum {
TTTMetricSystem = 0,
TTTImperialSystem,
} TTTLocationUnitSystem;
@interface TTTLocationFormatter : NSFormatter {
TTTLocationFormatterCoordinateOrder _coordinateOrder;
TTTLocationFormatterBearingStyle _bearingStyle;
TTTLocationUnitSystem _unitSystem;
NSNumberFormatter *_numberFormatter;
}
@property (readonly, nonatomic, retain) NSNumberFormatter *numberFormatter;
- (NSString *)stringFromCoordinate:(CLLocationCoordinate2D)coordinate;
- (NSString *)stringFromLocation:(CLLocation *)location;
- (NSString *)stringFromDistance:(CLLocationDistance)distance;
- (NSString *)stringFromBearing:(CLLocationDegrees)bearing;
- (NSString *)stringFromSpeed:(CLLocationSpeed)speed;
- (NSString *)stringFromDistanceFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation;
- (NSString *)stringFromBearingFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation;
- (NSString *)stringFromDistanceAndBearingFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation;
- (NSString *)stringFromVelocityFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation atSpeed:(CLLocationSpeed)speed;
- (TTTLocationFormatterCoordinateOrder)coordinateOrder;
- (void)setCoordinateOrder:(TTTLocationFormatterCoordinateOrder)coordinateOrder;
- (TTTLocationFormatterBearingStyle)bearingStyle;
- (void)setBearingStyle:(TTTLocationFormatterBearingStyle)bearingStyle;
- (TTTLocationUnitSystem)unitSystem;
- (void)setUnitSystem:(TTTLocationUnitSystem)unitSystem;
@end

View file

@ -0,0 +1,299 @@
// TTTLocationFormatter.m
//
// Copyright (c) 2011 Mattt Thompson (http://mattt.me)
//
// 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 "TTTLocationFormatter.h"
static double const kTTTMetersToKilometersCoefficient = 0.001;
static double const kTTTMetersToFeetCoefficient = 3.2808399;
static double const kTTTMetersToYardsCoefficient = 1.0936133;
static double const kTTTMetersToMilesCoefficient = 0.000621371192;
static inline double CLLocationDistanceToKilometers(CLLocationDistance distance) {
return distance * kTTTMetersToKilometersCoefficient;
}
static inline double CLLocationDistanceToFeet(CLLocationDistance distance) {
return distance * kTTTMetersToFeetCoefficient;
}
static inline double CLLocationDistanceToYards(CLLocationDistance distance) {
return distance * kTTTMetersToYardsCoefficient;
}
static inline double CLLocationDistanceToMiles(CLLocationDistance distance) {
return distance * kTTTMetersToMilesCoefficient;
}
#pragma mark -
static inline double DEG2RAD(double degrees) {
return degrees * M_PI / 180;
}
static inline double RAD2DEG(double radians) {
return radians * 180 / M_PI;
}
static inline CLLocationDegrees CLLocationDegreesBearingBetweenCoordinates(CLLocationCoordinate2D originCoordinate, CLLocationCoordinate2D destinationCoordinate) {
double lat1 = DEG2RAD(originCoordinate.latitude);
double lon1 = DEG2RAD(originCoordinate.longitude);
double lat2 = DEG2RAD(destinationCoordinate.latitude);
double lon2 = DEG2RAD(destinationCoordinate.longitude);
double dLon = lon2 - lon1;
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double bearing = atan2(y, x) + (2 * M_PI);
// `atan2` works on a range of -π to 0 to π, so add on 2π and perform a modulo check
if (bearing > (2 * M_PI)) {
bearing = bearing - (2 * M_PI);
}
return RAD2DEG(bearing);
}
TTTLocationCardinalDirection TTTLocationCardinalDirectionFromBearing(CLLocationDegrees bearing) {
if(bearing > 337.5) {
return TTTNorthDirection;
} else if(bearing > 292.5) {
return TTTNorthwestDirection;
} else if(bearing > 247.5) {
return TTTWestDirection;
} else if(bearing > 202.5) {
return TTTSouthwestDirection;
} else if(bearing > 157.5) {
return TTTSouthDirection;
} else if(bearing > 112.5) {
return TTTSoutheastDirection;
} else if(bearing > 67.5) {
return TTTEastDirection;
} else if(bearing > 22.5) {
return TTTNortheastDirection;
} else {
return TTTNorthDirection;
}
}
#pragma mark -
static double const kTTTMetersPerSecondToKilometersPerHourCoefficient = 3.6;
static double const kTTTMetersPerSecondToFeetPerSecondCoefficient = 3.2808399;
static double const kTTTMetersPerSecondToMilesPerHourCoefficient = 2.23693629;
static inline double CLLocationSpeedToKilometersPerHour(CLLocationSpeed speed) {
return speed * kTTTMetersPerSecondToKilometersPerHourCoefficient;
}
static inline double CLLocationSpeedToFeetPerSecond(CLLocationSpeed speed) {
return speed * kTTTMetersPerSecondToFeetPerSecondCoefficient;
}
static inline double CLLocationSpeedToMilesPerHour(CLLocationSpeed speed) {
return speed * kTTTMetersPerSecondToMilesPerHourCoefficient;
}
@interface TTTLocationFormatter ()
@property (readwrite, nonatomic, assign) TTTLocationFormatterCoordinateOrder coordinateOrder;
@property (readwrite, nonatomic, assign) TTTLocationFormatterBearingStyle bearingStyle;
@property (readwrite, nonatomic, assign) TTTLocationUnitSystem unitSystem;
@property (readwrite, nonatomic, retain) NSNumberFormatter *numberFormatter;
@end
@implementation TTTLocationFormatter
@synthesize coordinateOrder = _coordinateOrder;
@synthesize bearingStyle = _bearingStyle;
@synthesize unitSystem = _unitSystem;
@synthesize numberFormatter = _numberFormatter;
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.coordinateOrder = TTTCoordinateLatLngOrder;
self.bearingStyle = TTTBearingWordStyle;
self.unitSystem = TTTMetricSystem;
self.numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[self.numberFormatter setLocale:[NSLocale currentLocale]];
[self.numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[self.numberFormatter setMaximumSignificantDigits:2];
[self.numberFormatter setUsesSignificantDigits:YES];
return self;
}
- (NSString *)stringFromCoordinate:(CLLocationCoordinate2D)coordinate {
return [NSString stringWithFormat:NSLocalizedString(@"(%@, %@)", @"Coordinate format"), [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:coordinate.latitude]], [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:coordinate.longitude]], nil];
}
- (NSString *)stringFromLocation:(CLLocation *)location {
return [self stringFromCoordinate:location.coordinate];
}
- (NSString *)stringFromDistance:(CLLocationDistance)distance {
NSString *distanceString = nil;
NSString *unitString = nil;
switch (self.unitSystem) {
case TTTMetricSystem: {
double kilometerDistance = CLLocationDistanceToKilometers(distance);
if (kilometerDistance > 1) {
distanceString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:kilometerDistance]];
unitString = NSLocalizedString(@"km", @"Kilometer Unit");
} else {
double meterDistance = distance;
distanceString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:meterDistance]];
unitString = NSLocalizedString(@"m", @"Meter Unit");
}
break;
}
case TTTImperialSystem: {
double feetDistance = CLLocationDistanceToFeet(distance);
if (feetDistance < 300) {
distanceString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:feetDistance]];
unitString = NSLocalizedString(@"ft", @"Feet Unit");
} else {
double yardDistance = CLLocationDistanceToYards(distance);
if (yardDistance < 500) {
distanceString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:yardDistance]];
unitString = NSLocalizedString(@"yds", @"Yard Unit");
} else {
double milesDistance = CLLocationDistanceToMiles(distance);
distanceString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:milesDistance]];
unitString = (milesDistance > 1.0 && milesDistance < 1.1) ? NSLocalizedString(@"mile", @"Mile Unit (Singular)") : NSLocalizedString(@"miles", @"Mile Unit (Plural)");
}
}
break;
}
}
return [NSString stringWithFormat:NSLocalizedString(@"%@ %@", @"#{Distance} #{Unit}"), distanceString, unitString];
}
- (NSString *)stringFromBearing:(CLLocationDegrees)bearing {
switch (self.bearingStyle) {
case TTTBearingWordStyle:
switch (TTTLocationCardinalDirectionFromBearing(bearing)) {
case TTTNorthDirection:
return NSLocalizedString(@"North", @"North Direction");
case TTTNortheastDirection:
return NSLocalizedString(@"Northeast", @"Northeast Direction");
case TTTEastDirection:
return NSLocalizedString(@"East", @"East Direction");
case TTTSoutheastDirection:
return NSLocalizedString(@"Southeast", @"Southeast Direction");
case TTTSouthDirection:
return NSLocalizedString(@"South", @"South Direction");
case TTTSouthwestDirection:
return NSLocalizedString(@"Southwest", @"Southwest Direction");
case TTTWestDirection:
return NSLocalizedString(@"West", @"West Direction");
case TTTNorthwestDirection:
return NSLocalizedString(@"Northwest", @"Northwest Direction");
}
break;
case TTTBearingAbbreviationWordStyle:
switch (TTTLocationCardinalDirectionFromBearing(bearing)) {
case TTTNorthDirection:
return NSLocalizedString(@"N", @"North Direction Abbreviation");
case TTTNortheastDirection:
return NSLocalizedString(@"NE", @"Northeast Direction Abbreviation");
case TTTEastDirection:
return NSLocalizedString(@"E", @"East Direction Abbreviation");
case TTTSoutheastDirection:
return NSLocalizedString(@"SE", @"Southeast Direction Abbreviation");
case TTTSouthDirection:
return NSLocalizedString(@"S", @"South Direction Abbreviation");
case TTTSouthwestDirection:
return NSLocalizedString(@"SW", @"Southwest Direction Abbreviation");
case TTTWestDirection:
return NSLocalizedString(@"W", @"West Direction Abbreviation");
case TTTNorthwestDirection:
return NSLocalizedString(@"NW", @"Northwest Direction Abbreviation");;
}
break;
case TTTBearingNumericStyle:
return [[self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:bearing]] stringByAppendingString:NSLocalizedString(@"°", @"Degrees Symbol")];
}
return nil;
}
- (NSString *)stringFromSpeed:(CLLocationSpeed)speed {
NSString *speedString = nil;
NSString *unitString = nil;
switch (self.unitSystem) {
case TTTMetricSystem: {
double metersPerSecondSpeed = speed;
double kilometersPerHourSpeed = CLLocationSpeedToKilometersPerHour(speed);
if (kilometersPerHourSpeed > 1) {
speedString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:kilometersPerHourSpeed]];
unitString = NSLocalizedString(@"km/h", @"Kilometers Per Hour Unit");
} else {
speedString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:metersPerSecondSpeed]];
unitString = NSLocalizedString(@"m/s", @"Meters Per Second Unit");
}
break;
}
case TTTImperialSystem: {
double feetPerSecondSpeed = CLLocationSpeedToFeetPerSecond(speed);
double milesPerHourSpeed = CLLocationSpeedToMilesPerHour(speed);
if (milesPerHourSpeed > 1) {
speedString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:milesPerHourSpeed]];
unitString = NSLocalizedString(@"mph", @"Miles Per Hour Unit");
} else {
speedString = [self.numberFormatter stringFromNumber:[NSNumber numberWithDouble:feetPerSecondSpeed]];
unitString = NSLocalizedString(@"ft/s", @"Feet Per Second Unit");
}
break;
}
}
return [NSString stringWithFormat:NSLocalizedString(@"%@ %@", @"#{Speed} #{Unit}"), speedString, unitString];
}
- (NSString *)stringFromDistanceFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation {
return [self stringFromDistance:[destinationLocation distanceFromLocation:originLocation]];
}
- (NSString *)stringFromBearingFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation {
return [self stringFromBearing:CLLocationDegreesBearingBetweenCoordinates(originLocation.coordinate, destinationLocation.coordinate)];
}
- (NSString *)stringFromDistanceAndBearingFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation {
return [NSString stringWithFormat:NSLocalizedString(@"%@ %@", @"#{Dimensional Quantity} #{Direction}"), [self stringFromDistanceFromLocation:originLocation toLocation:destinationLocation], [self stringFromBearingFromLocation:originLocation toLocation:destinationLocation]];
}
- (NSString *)stringFromVelocityFromLocation:(CLLocation *)originLocation toLocation:(CLLocation *)destinationLocation atSpeed:(CLLocationSpeed)speed {
return [NSString stringWithFormat:NSLocalizedString(@"%@ %@", @"#{Dimensional Quantity} #{Direction}"), [self stringFromSpeed:speed], [self stringFromBearingFromLocation:originLocation toLocation:destinationLocation]];
}
@end