From 251ce062f2159de90f78926c33cecd87e85d0342 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Fri, 16 Sep 2011 10:36:36 -0500 Subject: [PATCH 01/65] Stashing XML Request Operation --- AFNetworking/AFJSONRequestOperation.m | 2 +- .../project.pbxproj | 6 + Example/AFXMLRequestOperation.h | 23 ++++ Example/AFXMLRequestOperation.m | 111 ++++++++++++++++++ 4 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 Example/AFXMLRequestOperation.h create mode 100644 Example/AFXMLRequestOperation.m diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 0baabd8..5987a0c 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -28,7 +28,7 @@ static dispatch_queue_t af_json_request_operation_processing_queue; static dispatch_queue_t json_request_operation_processing_queue() { if (af_json_request_operation_processing_queue == NULL) { - af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.json-request.processing", 0); + af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0); } return af_json_request_operation_processing_queue; diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index b61798d..26a50bb 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -18,6 +18,7 @@ F874B5DE13E0AA6500B28E3E /* AFRestClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CE13E0AA6500B28E3E /* AFRestClient.m */; }; F874B5DF13E0AA6500B28E3E /* UIImage+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CF13E0AA6500B28E3E /* UIImage+AFNetworking.m */; }; F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */; }; + F8870C0F1423A15900BCD863 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */; }; F8D25D191396A9D300CF3BD6 /* placeholder-stamp.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D171396A9D300CF3BD6 /* placeholder-stamp.png */; }; F8D25D1A1396A9D300CF3BD6 /* placeholder-stamp@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D181396A9D300CF3BD6 /* placeholder-stamp@2x.png */; }; F8DA09D21396ABED0057D0CC /* AFGowallaAPIClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */; }; @@ -58,6 +59,8 @@ F874B5D613E0AA6500B28E3E /* AFRestClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; lineEnding = 0; name = AFRestClient.h; path = ../AFNetworking/AFRestClient.h; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.objcpp; }; F874B5D713E0AA6500B28E3E /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImage+AFNetworking.h"; path = "../AFNetworking/UIImage+AFNetworking.h"; sourceTree = ""; }; F874B5D813E0AA6500B28E3E /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "../AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + F8870C0D1423A15800BCD863 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFXMLRequestOperation.h; sourceTree = ""; }; + F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = ""; }; F8D25D101396A9C400CF3BD6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; F8D25D111396A9C400CF3BD6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; F8D25D131396A9C400CF3BD6 /* TTTLocationFormatter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TTTLocationFormatter.h; sourceTree = ""; }; @@ -247,6 +250,8 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, + F8870C0D1423A15800BCD863 /* AFXMLRequestOperation.h */, + F8870C0E1423A15800BCD863 /* AFXMLRequestOperation.m */, F874B5D613E0AA6500B28E3E /* AFRestClient.h */, F874B5CE13E0AA6500B28E3E /* AFRestClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, @@ -361,6 +366,7 @@ F85CE2D413EC478F00BFAE01 /* NSString+AFNetworking.m in Sources */, F85CE2DC13EC4A4200BFAE01 /* NSMutableURLRequest+AFNetworking.m in Sources */, F85CE55513EC759200BFAE01 /* NSData+AFNetworking.m in Sources */, + F8870C0F1423A15900BCD863 /* AFXMLRequestOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Example/AFXMLRequestOperation.h b/Example/AFXMLRequestOperation.h new file mode 100644 index 0000000..72b5221 --- /dev/null +++ b/Example/AFXMLRequestOperation.h @@ -0,0 +1,23 @@ +// AFXMLRequestOperation.h + +#import "AFHTTPRequestOperation.h" + +@interface AFXMLRequestOperation : AFHTTPRequestOperation + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success; + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success + failure:(void (^)(NSError *error))failure; + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes + acceptableContentTypes:(NSSet *)acceptableContentTypes + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id XML))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + ++ (NSIndexSet *)defaultAcceptableStatusCodes; ++ (NSSet *)defaultAcceptableContentTypes; + +@end diff --git a/Example/AFXMLRequestOperation.m b/Example/AFXMLRequestOperation.m new file mode 100644 index 0000000..a1c03ae --- /dev/null +++ b/Example/AFXMLRequestOperation.m @@ -0,0 +1,111 @@ +// AFXMLRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFXMLRequestOperation.h" + +#include + +static dispatch_queue_t af_xml_request_operation_processing_queue; +static dispatch_queue_t xml_request_operation_processing_queue() { + if (af_xml_request_operation_processing_queue == NULL) { + af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0); + } + + return af_xml_request_operation_processing_queue; +} + +@implementation AFXMLRequestOperation + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success +{ + return [self operationWithRequest:urlRequest success:success failure:nil]; +} + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id XML))success + failure:(void (^)(NSError *error))failure +{ + return [self operationWithRequest:urlRequest acceptableStatusCodes:[self defaultAcceptableStatusCodes] acceptableContentTypes:[self defaultAcceptableContentTypes] success:^(NSURLRequest *request, NSHTTPURLResponse *response, id XML) { + if (success) { + success(XML); + } + } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { + if (failure) { + failure(error); + } + }]; +} + ++ (id)operationWithRequest:(NSURLRequest *)urlRequest + acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes + acceptableContentTypes:(NSSet *)acceptableContentTypes + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + return [self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { + if (!error) { + if (![acceptableStatusCodes containsIndex:[response statusCode]]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), acceptableStatusCodes, [response statusCode]] forKey:NSLocalizedDescriptionKey]; + [userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey]; + + error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease]; + } + + if (![acceptableContentTypes containsObject:[response MIMEType]]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), acceptableContentTypes, [response MIMEType]] forKey:NSLocalizedDescriptionKey]; + [userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey]; + + error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease]; + } + } + + if (error) { + if (failure) { + failure(request, response, error); + } + } else if ([data length] == 0) { + if (success) { + success(request, response, nil); + } + } else { + dispatch_async(xml_request_operation_processing_queue(), ^(void) { + id XML = nil; + NSError *XMLError = nil; + + + }); + } + }]; +} + ++ (NSIndexSet *)defaultAcceptableStatusCodes { + return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; +} + ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; +} + +@end From efdaedc54103a0ae8c7145c5c023b46b1bc824ae Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Fri, 23 Sep 2011 12:19:40 -0500 Subject: [PATCH 02/65] Adding Mac example project Renaming iOS example project Adding AFNetworking to Mac project using preprocessor macros to resolve UIKit dependencies, and setting compiler flags accordingly. --- AFNetworking/AFHTTPClient.m | 4 +- AFNetworking/AFHTTPRequestOperation.m | 2 + AFNetworking/AFImageCache.h | 8 + AFNetworking/AFImageCache.m | 4 + AFNetworking/AFImageRequestOperation.h | 9 +- AFNetworking/AFImageRequestOperation.m | 4 + .../AFNetworkActivityIndicatorManager.h | 3 + .../AFNetworkActivityIndicatorManager.m | 2 + AFNetworking/UIImageView+AFNetworking.h | 4 + AFNetworking/UIImageView+AFNetworking.m | 3 + .../project.pbxproj | 359 ++ .../AFNetworking Mac Example.xcscheme | 75 + .../xcschemes/xcschememanagement.plist | 22 + .../AFNetworking_Mac_ExampleAppDelegate.h | 17 + .../AFNetworking_Mac_ExampleAppDelegate.m | 20 + .../AFNetworking Mac Example/Info.plist | 36 + .../AFNetworking Mac Example/Prefix.pch | 7 + .../Vendor/JSONKit/JSONKit.h | 0 .../Vendor/JSONKit/JSONKit.m | 0 .../Vendor/TTT/TTTLocationFormatter.h | 0 .../Vendor/TTT/TTTLocationFormatter.m | 0 .../en.lproj/Credits.rtf | 29 + .../en.lproj/MainMenu.xib | 5627 +++++++++++++++++ Mac Example/AFNetworking Mac Example/main.m | 14 + .../project.pbxproj | 0 .../xcdebugger/Breakpoints.xcbkptlist | 0 .../xcschemes/AFNetworking Example.xcscheme | 0 .../xcschemes/xcschememanagement.plist | 0 {Example => iOS Example}/AppDelegate.h | 0 {Example => iOS Example}/AppDelegate.m | 0 .../Classes/AFGowallaAPIClient.h | 0 .../Classes/AFGowallaAPIClient.m | 0 .../Controllers/NearbySpotsViewController.h | 0 .../Controllers/NearbySpotsViewController.m | 0 .../Classes/Models/Spot.h | 0 .../Classes/Models/Spot.m | 0 .../Classes/Views/SpotTableViewCell.h | 0 .../Classes/Views/SpotTableViewCell.m | 0 .../Images/placeholder-stamp.png | Bin .../Images/placeholder-stamp@2x.png | Bin {Example => iOS Example}/Info.plist | 0 {Example => iOS Example}/Prefix.pch | 0 iOS Example/Vendor/JSONKit/JSONKit.h | 251 + iOS Example/Vendor/JSONKit/JSONKit.m | 3011 +++++++++ iOS Example/Vendor/TTT/TTTLocationFormatter.h | 83 + iOS Example/Vendor/TTT/TTTLocationFormatter.m | 299 + {Example => iOS Example}/main.m | 0 47 files changed, 9890 insertions(+), 3 deletions(-) create mode 100644 Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj create mode 100644 Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Mac Example.xcscheme create mode 100644 Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h create mode 100644 Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m create mode 100644 Mac Example/AFNetworking Mac Example/Info.plist create mode 100644 Mac Example/AFNetworking Mac Example/Prefix.pch rename {Example => Mac Example/AFNetworking Mac Example}/Vendor/JSONKit/JSONKit.h (100%) rename {Example => Mac Example/AFNetworking Mac Example}/Vendor/JSONKit/JSONKit.m (100%) rename {Example => Mac Example/AFNetworking Mac Example}/Vendor/TTT/TTTLocationFormatter.h (100%) rename {Example => Mac Example/AFNetworking Mac Example}/Vendor/TTT/TTTLocationFormatter.m (100%) create mode 100644 Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf create mode 100644 Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib create mode 100644 Mac Example/AFNetworking Mac Example/main.m rename {Example/AFNetworking Example.xcodeproj => iOS Example/AFNetworking iOS Example.xcodeproj}/project.pbxproj (100%) rename {Example/AFNetworking Example.xcodeproj => iOS Example/AFNetworking iOS Example.xcodeproj}/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist (100%) rename {Example/AFNetworking Example.xcodeproj => iOS Example/AFNetworking iOS Example.xcodeproj}/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme (100%) rename {Example/AFNetworking Example.xcodeproj => iOS Example/AFNetworking iOS Example.xcodeproj}/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist (100%) rename {Example => iOS Example}/AppDelegate.h (100%) rename {Example => iOS Example}/AppDelegate.m (100%) rename {Example => iOS Example}/Classes/AFGowallaAPIClient.h (100%) rename {Example => iOS Example}/Classes/AFGowallaAPIClient.m (100%) rename {Example => iOS Example}/Classes/Controllers/NearbySpotsViewController.h (100%) rename {Example => iOS Example}/Classes/Controllers/NearbySpotsViewController.m (100%) rename {Example => iOS Example}/Classes/Models/Spot.h (100%) rename {Example => iOS Example}/Classes/Models/Spot.m (100%) rename {Example => iOS Example}/Classes/Views/SpotTableViewCell.h (100%) rename {Example => iOS Example}/Classes/Views/SpotTableViewCell.m (100%) rename {Example => iOS Example}/Images/placeholder-stamp.png (100%) rename {Example => iOS Example}/Images/placeholder-stamp@2x.png (100%) rename {Example => iOS Example}/Info.plist (100%) rename {Example => iOS Example}/Prefix.pch (100%) create mode 100644 iOS Example/Vendor/JSONKit/JSONKit.h create mode 100644 iOS Example/Vendor/JSONKit/JSONKit.m create mode 100644 iOS Example/Vendor/TTT/TTTLocationFormatter.h create mode 100644 iOS Example/Vendor/TTT/TTTLocationFormatter.m rename {Example => iOS Example}/main.m (100%) diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 52818ea..fc17b32 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -119,8 +119,8 @@ 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)]]; +// // 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)]]; self.operationQueue = [[[NSOperationQueue alloc] init] autorelease]; [self.operationQueue setMaxConcurrentOperationCount:2]; diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 11eb2c2..9f1d8ee 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -225,6 +225,7 @@ static NSThread *_networkRequestThread = nil; [self didChangeValueForKey:oldStateKey]; [self didChangeValueForKey:newStateKey]; +#if __IPHONE_OS_VERSION_MIN_REQUIRED switch (state) { case AFHTTPOperationExecutingState: [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount]; @@ -237,6 +238,7 @@ static NSThread *_networkRequestThread = nil; default: break; } +#endif } - (void)setCancelled:(BOOL)cancelled { diff --git a/AFNetworking/AFImageCache.h b/AFNetworking/AFImageCache.h index 08d9e3f..66c0044 100644 --- a/AFNetworking/AFImageCache.h +++ b/AFNetworking/AFImageCache.h @@ -23,6 +23,8 @@ #import #import "AFImageRequestOperation.h" +#import + /** `AFImageCache` is a subclass of `NSCache` that stores and retrieves images from cache. @@ -45,8 +47,11 @@ @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; +#endif /** Stores an image into cache, associated with a given URL and cache name. @@ -55,8 +60,11 @@ @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; +#endif @end diff --git a/AFNetworking/AFImageCache.m b/AFNetworking/AFImageCache.m index de74346..b62e5bc 100644 --- a/AFNetworking/AFImageCache.m +++ b/AFNetworking/AFImageCache.m @@ -39,12 +39,15 @@ 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)]; } +#endif +#if __IPHONE_OS_VERSION_MIN_REQUIRED - (void)cacheImage:(UIImage *)image forURL:(NSURL *)url cacheName:(NSString *)cacheName @@ -55,5 +58,6 @@ static inline NSString * AFImageCacheKeyFromURLAndCacheName(NSURL *url, NSString [self setObject:image forKey:AFImageCacheKeyFromURLAndCacheName(url, cacheName)]; } +#endif @end diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 77760a5..2069045 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -21,9 +21,10 @@ // THE SOFTWARE. #import -#import #import "AFHTTPRequestOperation.h" +#import + /** `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. @@ -40,8 +41,11 @@ @return A new image request operation */ + +#if __IPHONE_OS_VERSION_MIN_REQUIRED + (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success; +#endif /** Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. @@ -54,10 +58,13 @@ @return A new image request operation */ + +#if __IPHONE_OS_VERSION_MIN_REQUIRED + (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; +#endif @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 0e4d702..a54e740 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -34,6 +34,8 @@ static dispatch_queue_t image_request_operation_processing_queue() { @implementation AFImageRequestOperation +#if __IPHONE_OS_VERSION_MIN_REQUIRED + + (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success { @@ -85,4 +87,6 @@ static dispatch_queue_t image_request_operation_processing_queue() { }]; } +#endif + @end diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.h b/AFNetworking/AFNetworkActivityIndicatorManager.h index 59110b9..9bd0ce5 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.h +++ b/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -25,6 +25,8 @@ /** `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When network operations start, they can call `-incrementActivityCount`, and once they're finished, call `-decrementActivityCount`. 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. */ + +#if __IPHONE_OS_VERSION_MIN_REQUIRED @interface AFNetworkActivityIndicatorManager : NSObject { @private NSInteger _activityCount; @@ -48,3 +50,4 @@ - (void)decrementActivityCount; @end +#endif \ No newline at end of file diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index 89d12cb..da6a0d3 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -22,6 +22,7 @@ #import "AFNetworkActivityIndicatorManager.h" +#if __IPHONE_OS_VERSION_MIN_REQUIRED @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; @end @@ -60,3 +61,4 @@ } @end +#endif diff --git a/AFNetworking/UIImageView+AFNetworking.h b/AFNetworking/UIImageView+AFNetworking.h index 4b6d72b..03e14f5 100644 --- a/AFNetworking/UIImageView+AFNetworking.h +++ b/AFNetworking/UIImageView+AFNetworking.h @@ -20,6 +20,9 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED #import #import "AFImageRequestOperation.h" @@ -71,3 +74,4 @@ - (void)cancelImageRequestOperation; @end +#endif diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index d03c178..252e904 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -23,6 +23,8 @@ #import #import +#if __IPHONE_OS_VERSION_MIN_REQUIRED + #import "UIImageView+AFNetworking.h" #import "AFImageCache.h" @@ -170,3 +172,4 @@ static NSString * const kUIImageViewImageRequestObjectKey = @"_af_imageRequestOp } @end +#endif diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b1fc532 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -0,0 +1,359 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + F8A27A2C142CF24700F5E0D6 /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A2D142CF24700F5E0D6 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A2E142CF24700F5E0D6 /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A23142CF24700F5E0D6 /* AFImageCache.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A2F142CF24700F5E0D6 /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A30142CF24700F5E0D6 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A31142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A32142CF24700F5E0D6 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27A3A142CF36100F5E0D6 /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A39142CF36100F5E0D6 /* JSONKit.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */; }; + F8CEEB7B142CEC6E00247B03 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB7A142CEC6E00247B03 /* main.m */; }; + F8CEEB7F142CEC6E00247B03 /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB7D142CEC6E00247B03 /* Credits.rtf */; }; + F8CEEB82142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */; }; + F8CEEB85142CEC6E00247B03 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB83142CEC6E00247B03 /* MainMenu.xib */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + F8A27A1E142CF24700F5E0D6 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = AFNetworking/AFHTTPClient.h; sourceTree = ""; }; + F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = AFNetworking/AFHTTPClient.m; sourceTree = ""; }; + F8A27A20142CF24700F5E0D6 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = AFNetworking/AFHTTPRequestOperation.h; sourceTree = ""; }; + F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; + F8A27A22142CF24700F5E0D6 /* AFImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageCache.h; path = AFNetworking/AFImageCache.h; sourceTree = ""; }; + F8A27A23142CF24700F5E0D6 /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = AFNetworking/AFImageCache.m; sourceTree = ""; }; + F8A27A24142CF24700F5E0D6 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageRequestOperation.h; path = AFNetworking/AFImageRequestOperation.h; sourceTree = ""; }; + F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = AFNetworking/AFImageRequestOperation.m; sourceTree = ""; }; + F8A27A26142CF24700F5E0D6 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFJSONRequestOperation.h; path = AFNetworking/AFJSONRequestOperation.h; sourceTree = ""; }; + F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFJSONRequestOperation.m; path = AFNetworking/AFJSONRequestOperation.m; sourceTree = ""; }; + F8A27A28142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = AFNetworking/AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; + F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = AFNetworking/AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; + F8A27A2A142CF24700F5E0D6 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; + F8A27A38142CF36100F5E0D6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; + F8A27A39142CF36100F5E0D6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; + 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; }; + F8CEEB76142CEC6E00247B03 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F8CEEB7A142CEC6E00247B03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + F8CEEB7C142CEC6E00247B03 /* Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; + F8CEEB7E142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = en; path = en.lproj/Credits.rtf; sourceTree = ""; }; + F8CEEB80142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFNetworking_Mac_ExampleAppDelegate.h; sourceTree = ""; }; + F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworking_Mac_ExampleAppDelegate.m; sourceTree = ""; }; + F8CEEB84142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/MainMenu.xib; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + F8CEEB67142CEC6E00247B03 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + F8A27A37142CF36000F5E0D6 /* JSONKit */ = { + isa = PBXGroup; + children = ( + F8A27A38142CF36100F5E0D6 /* JSONKit.h */, + F8A27A39142CF36100F5E0D6 /* JSONKit.m */, + ); + name = JSONKit; + path = "AFNetworking Mac Example/Vendor/JSONKit"; + sourceTree = ""; + }; + F8CEEB5F142CEC6E00247B03 = { + isa = PBXGroup; + children = ( + F8CEEB74142CEC6E00247B03 /* AFNetworking Mac Example */, + F8CEEB8B142CECAA00247B03 /* Vendor */, + F8CEEB6D142CEC6E00247B03 /* Frameworks */, + F8CEEB6B142CEC6E00247B03 /* Products */, + ); + sourceTree = ""; + }; + F8CEEB6B142CEC6E00247B03 /* Products */ = { + isa = PBXGroup; + children = ( + F8CEEB6A142CEC6E00247B03 /* AFNetworking Mac Example.app */, + ); + name = Products; + sourceTree = ""; + }; + F8CEEB6D142CEC6E00247B03 /* Frameworks */ = { + isa = PBXGroup; + children = ( + F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */, + F8CEEB70142CEC6E00247B03 /* Other Frameworks */, + ); + name = Frameworks; + sourceTree = ""; + }; + F8CEEB70142CEC6E00247B03 /* Other Frameworks */ = { + isa = PBXGroup; + children = ( + F8CEEB71142CEC6E00247B03 /* AppKit.framework */, + F8CEEB72142CEC6E00247B03 /* CoreData.framework */, + F8CEEB73142CEC6E00247B03 /* Foundation.framework */, + ); + name = "Other Frameworks"; + sourceTree = ""; + }; + F8CEEB74142CEC6E00247B03 /* AFNetworking Mac Example */ = { + isa = PBXGroup; + children = ( + F8CEEB80142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.h */, + F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */, + F8CEEB83142CEC6E00247B03 /* MainMenu.xib */, + F8CEEB75142CEC6E00247B03 /* Supporting Files */, + ); + path = "AFNetworking Mac Example"; + sourceTree = ""; + }; + F8CEEB75142CEC6E00247B03 /* Supporting Files */ = { + isa = PBXGroup; + children = ( + F8CEEB76142CEC6E00247B03 /* Info.plist */, + F8CEEB7A142CEC6E00247B03 /* main.m */, + F8CEEB7C142CEC6E00247B03 /* Prefix.pch */, + F8CEEB7D142CEC6E00247B03 /* Credits.rtf */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + F8CEEB8B142CECAA00247B03 /* Vendor */ = { + isa = PBXGroup; + children = ( + F8A27A37142CF36000F5E0D6 /* JSONKit */, + F8CEEB8C142CED6F00247B03 /* AFNetworking */, + ); + name = Vendor; + sourceTree = ""; + }; + F8CEEB8C142CED6F00247B03 /* AFNetworking */ = { + isa = PBXGroup; + children = ( + F8A27A20142CF24700F5E0D6 /* AFHTTPRequestOperation.h */, + F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */, + F8A27A26142CF24700F5E0D6 /* AFJSONRequestOperation.h */, + F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */, + F8A27A1E142CF24700F5E0D6 /* AFHTTPClient.h */, + F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */, + F8A27A22142CF24700F5E0D6 /* AFImageCache.h */, + F8A27A23142CF24700F5E0D6 /* AFImageCache.m */, + F8A27A24142CF24700F5E0D6 /* AFImageRequestOperation.h */, + F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */, + F8A27A28142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.h */, + F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */, + F8A27A2A142CF24700F5E0D6 /* UIImageView+AFNetworking.h */, + F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */, + ); + name = AFNetworking; + path = ../../AFNetworking; + sourceTree = ""; + }; +/* 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 = ( + F8CEEB7F142CEC6E00247B03 /* Credits.rtf in Resources */, + F8CEEB85142CEC6E00247B03 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + F8CEEB66142CEC6E00247B03 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F8CEEB7B142CEC6E00247B03 /* main.m in Sources */, + F8CEEB82142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m in Sources */, + F8A27A2C142CF24700F5E0D6 /* AFHTTPClient.m in Sources */, + F8A27A2D142CF24700F5E0D6 /* AFHTTPRequestOperation.m in Sources */, + F8A27A2E142CF24700F5E0D6 /* AFImageCache.m in Sources */, + F8A27A2F142CF24700F5E0D6 /* AFImageRequestOperation.m in Sources */, + F8A27A30142CF24700F5E0D6 /* AFJSONRequestOperation.m in Sources */, + F8A27A31142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m in Sources */, + F8A27A32142CF24700F5E0D6 /* UIImageView+AFNetworking.m in Sources */, + F8A27A3A142CF36100F5E0D6 /* JSONKit.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + F8CEEB7D142CEC6E00247B03 /* Credits.rtf */ = { + isa = PBXVariantGroup; + children = ( + F8CEEB7E142CEC6E00247B03 /* en */, + ); + name = Credits.rtf; + sourceTree = ""; + }; + F8CEEB83142CEC6E00247B03 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + F8CEEB84142CEC6E00247B03 /* en */, + ); + name = MainMenu.xib; + sourceTree = ""; + }; +/* 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 = "AFNetworking Mac Example/Prefix.pch"; + INFOPLIST_FILE = "AFNetworking Mac Example/Info.plist"; + PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; + }; + name = Debug; + }; + F8CEEB8A142CEC6E00247B03 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + GCC_PRECOMPILE_PREFIX_HEADER = YES; + GCC_PREFIX_HEADER = "AFNetworking Mac Example/Prefix.pch"; + INFOPLIST_FILE = "AFNetworking Mac Example/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 */; +} diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Mac Example.xcscheme b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Mac Example.xcscheme new file mode 100644 index 0000000..d4c1f1d --- /dev/null +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Mac Example.xcscheme @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..c675876 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ + + + + + SchemeUserState + + AFNetworking Mac Example.xcscheme + + orderHint + 0 + + + SuppressBuildableAutocreation + + F8CEEB69142CEC6E00247B03 + + primary + + + + + diff --git a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h b/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h new file mode 100644 index 0000000..6981127 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h @@ -0,0 +1,17 @@ +// +// AFNetworking_Mac_ExampleAppDelegate.h +// AFNetworking Mac Example +// +// Created by Mattt Thompson on 11/09/23. +// Copyright 2011年 Gowalla. All rights reserved. +// + +#import + +@interface AFNetworking_Mac_ExampleAppDelegate : NSObject { + NSWindow *_window; +} + +@property (strong) IBOutlet NSWindow *window; + +@end diff --git a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m b/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m new file mode 100644 index 0000000..fc334b8 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m @@ -0,0 +1,20 @@ +// +// AFNetworking_Mac_ExampleAppDelegate.m +// AFNetworking Mac Example +// +// Created by Mattt Thompson on 11/09/23. +// Copyright 2011年 Gowalla. All rights reserved. +// + +#import "AFNetworking_Mac_ExampleAppDelegate.h" + +@implementation AFNetworking_Mac_ExampleAppDelegate + +@synthesize window = _window; + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification +{ + // Insert code here to initialize your application +} + +@end diff --git a/Mac Example/AFNetworking Mac Example/Info.plist b/Mac Example/AFNetworking Mac Example/Info.plist new file mode 100644 index 0000000..c06d4a7 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + + CFBundleIdentifier + com.alamofire.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSApplicationCategoryType + public.app-category.utilities + LSMinimumSystemVersion + ${MACOSX_DEPLOYMENT_TARGET} + NSHumanReadableCopyright + Copyright © 2011 Gowalla. All rights reserved. + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/Mac Example/AFNetworking Mac Example/Prefix.pch b/Mac Example/AFNetworking Mac Example/Prefix.pch new file mode 100644 index 0000000..3027f95 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/Prefix.pch @@ -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 +#endif diff --git a/Example/Vendor/JSONKit/JSONKit.h b/Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.h similarity index 100% rename from Example/Vendor/JSONKit/JSONKit.h rename to Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.h diff --git a/Example/Vendor/JSONKit/JSONKit.m b/Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.m similarity index 100% rename from Example/Vendor/JSONKit/JSONKit.m rename to Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.m diff --git a/Example/Vendor/TTT/TTTLocationFormatter.h b/Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.h similarity index 100% rename from Example/Vendor/TTT/TTTLocationFormatter.h rename to Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.h diff --git a/Example/Vendor/TTT/TTTLocationFormatter.m b/Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.m similarity index 100% rename from Example/Vendor/TTT/TTTLocationFormatter.m rename to Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.m diff --git a/Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf b/Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf new file mode 100644 index 0000000..46576ef --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf @@ -0,0 +1,29 @@ +{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} +{\colortbl;\red255\green255\blue255;} +\paperw9840\paperh8400 +\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural + +\f0\b\fs24 \cf0 Engineering: +\b0 \ + Some people\ +\ + +\b Human Interface Design: +\b0 \ + Some other people\ +\ + +\b Testing: +\b0 \ + Hopefully not nobody\ +\ + +\b Documentation: +\b0 \ + Whoever\ +\ + +\b With special thanks to: +\b0 \ + Mom\ +} diff --git a/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib b/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib new file mode 100644 index 0000000..17c2105 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib @@ -0,0 +1,5627 @@ + + + + 1070 + 10J869 + 1839 + 1038.35 + 461.00 + + com.apple.InterfaceBuilder.CocoaPlugin + 1839 + + + YES + NSMenu + NSWindowTemplate + NSView + NSMenuItem + NSCustomObject + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + + + PluginDependencyRecalculationVersion + + + + YES + + NSApplication + + + FirstResponder + + + NSApplication + + + AMainMenu + + YES + + + AFNetworking Mac Example + + 1048576 + 2147483647 + + NSImage + NSMenuCheckmark + + + NSImage + NSMenuMixedState + + submenuAction: + + AFNetworking Mac Example + + YES + + + About AFNetworking Mac Example + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Preferences… + , + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Services + + 1048576 + 2147483647 + + + submenuAction: + + Services + + YES + + _NSServicesMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Hide AFNetworking Mac Example + h + 1048576 + 2147483647 + + + + + + Hide Others + h + 1572864 + 2147483647 + + + + + + Show All + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Quit AFNetworking Mac Example + q + 1048576 + 2147483647 + + + + + _NSAppleMenu + + + + + File + + 1048576 + 2147483647 + + + submenuAction: + + File + + YES + + + New + n + 1048576 + 2147483647 + + + + + + Open… + o + 1048576 + 2147483647 + + + + + + Open Recent + + 1048576 + 2147483647 + + + submenuAction: + + Open Recent + + YES + + + Clear Menu + + 1048576 + 2147483647 + + + + + _NSRecentDocumentsMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Close + w + 1048576 + 2147483647 + + + + + + Save… + s + 1048576 + 2147483647 + + + + + + Revert to Saved + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Page Setup... + P + 1179648 + 2147483647 + + + + + + + Print… + p + 1048576 + 2147483647 + + + + + + + + + Edit + + 1048576 + 2147483647 + + + submenuAction: + + Edit + + YES + + + Undo + z + 1048576 + 2147483647 + + + + + + Redo + Z + 1179648 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Cut + x + 1048576 + 2147483647 + + + + + + Copy + c + 1048576 + 2147483647 + + + + + + Paste + v + 1048576 + 2147483647 + + + + + + Paste and Match Style + V + 1572864 + 2147483647 + + + + + + Delete + + 1048576 + 2147483647 + + + + + + Select All + a + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Find + + 1048576 + 2147483647 + + + submenuAction: + + Find + + YES + + + Find… + f + 1048576 + 2147483647 + + + 1 + + + + Find and Replace… + f + 1572864 + 2147483647 + + + 12 + + + + Find Next + g + 1048576 + 2147483647 + + + 2 + + + + Find Previous + G + 1179648 + 2147483647 + + + 3 + + + + Use Selection for Find + e + 1048576 + 2147483647 + + + 7 + + + + Jump to Selection + j + 1048576 + 2147483647 + + + + + + + + + Spelling and Grammar + + 1048576 + 2147483647 + + + submenuAction: + + Spelling and Grammar + + YES + + + Show Spelling and Grammar + : + 1048576 + 2147483647 + + + + + + Check Document Now + ; + 1048576 + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + Check Spelling While Typing + + 1048576 + 2147483647 + + + + + + Check Grammar With Spelling + + 1048576 + 2147483647 + + + + + + Correct Spelling Automatically + + 2147483647 + + + + + + + + + Substitutions + + 1048576 + 2147483647 + + + submenuAction: + + Substitutions + + YES + + + Show Substitutions + + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + Smart Copy/Paste + f + 1048576 + 2147483647 + + + 1 + + + + Smart Quotes + g + 1048576 + 2147483647 + + + 2 + + + + Smart Dashes + + 2147483647 + + + + + + Smart Links + G + 1179648 + 2147483647 + + + 3 + + + + Text Replacement + + 2147483647 + + + + + + + + + Transformations + + 2147483647 + + + submenuAction: + + Transformations + + YES + + + Make Upper Case + + 2147483647 + + + + + + Make Lower Case + + 2147483647 + + + + + + Capitalize + + 2147483647 + + + + + + + + + Speech + + 1048576 + 2147483647 + + + submenuAction: + + Speech + + YES + + + Start Speaking + + 1048576 + 2147483647 + + + + + + Stop Speaking + + 1048576 + 2147483647 + + + + + + + + + + + + Format + + 2147483647 + + + submenuAction: + + Format + + YES + + + Font + + 2147483647 + + + submenuAction: + + Font + + YES + + + Show Fonts + t + 1048576 + 2147483647 + + + + + + Bold + b + 1048576 + 2147483647 + + + 2 + + + + Italic + i + 1048576 + 2147483647 + + + 1 + + + + Underline + u + 1048576 + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + Bigger + + + 1048576 + 2147483647 + + + 3 + + + + Smaller + - + 1048576 + 2147483647 + + + 4 + + + + YES + YES + + + 2147483647 + + + + + + Kern + + 2147483647 + + + submenuAction: + + Kern + + YES + + + Use Default + + 2147483647 + + + + + + Use None + + 2147483647 + + + + + + Tighten + + 2147483647 + + + + + + Loosen + + 2147483647 + + + + + + + + + Ligature + + 2147483647 + + + submenuAction: + + Ligature + + YES + + + Use Default + + 2147483647 + + + + + + Use None + + 2147483647 + + + + + + Use All + + 2147483647 + + + + + + + + + Baseline + + 2147483647 + + + submenuAction: + + Baseline + + YES + + + Use Default + + 2147483647 + + + + + + Superscript + + 2147483647 + + + + + + Subscript + + 2147483647 + + + + + + Raise + + 2147483647 + + + + + + Lower + + 2147483647 + + + + + + + + + YES + YES + + + 2147483647 + + + + + + Show Colors + C + 1048576 + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + Copy Style + c + 1572864 + 2147483647 + + + + + + Paste Style + v + 1572864 + 2147483647 + + + + + _NSFontMenu + + + + + Text + + 2147483647 + + + submenuAction: + + Text + + YES + + + Align Left + { + 1048576 + 2147483647 + + + + + + Center + | + 1048576 + 2147483647 + + + + + + Justify + + 2147483647 + + + + + + Align Right + } + 1048576 + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + Writing Direction + + 2147483647 + + + submenuAction: + + Writing Direction + + YES + + + YES + Paragraph + + 2147483647 + + + + + + CURlZmF1bHQ + + 2147483647 + + + + + + CUxlZnQgdG8gUmlnaHQ + + 2147483647 + + + + + + CVJpZ2h0IHRvIExlZnQ + + 2147483647 + + + + + + YES + YES + + + 2147483647 + + + + + + YES + Selection + + 2147483647 + + + + + + CURlZmF1bHQ + + 2147483647 + + + + + + CUxlZnQgdG8gUmlnaHQ + + 2147483647 + + + + + + CVJpZ2h0IHRvIExlZnQ + + 2147483647 + + + + + + + + + YES + YES + + + 2147483647 + + + + + + Show Ruler + + 2147483647 + + + + + + Copy Ruler + c + 1310720 + 2147483647 + + + + + + Paste Ruler + v + 1310720 + 2147483647 + + + + + + + + + + + + View + + 1048576 + 2147483647 + + + submenuAction: + + View + + YES + + + Show Toolbar + t + 1572864 + 2147483647 + + + + + + Customize Toolbar… + + 1048576 + 2147483647 + + + + + + + + + Window + + 1048576 + 2147483647 + + + submenuAction: + + Window + + YES + + + Minimize + m + 1048576 + 2147483647 + + + + + + Zoom + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Bring All to Front + + 1048576 + 2147483647 + + + + + _NSWindowsMenu + + + + + Help + + 2147483647 + + + submenuAction: + + Help + + YES + + + AFNetworking Mac Example Help + ? + 1048576 + 2147483647 + + + + + _NSHelpMenu + + + + _NSMainMenu + + + 15 + 2 + {{335, 390}, {480, 360}} + 1954021376 + AFNetworking Mac Example + NSWindow + + + + 256 + {480, 360} + + {{0, 0}, {1920, 1178}} + {1e+13, 1e+13} + + + AFNetworking_Mac_ExampleAppDelegate + + + NSFontManager + + + + + YES + + + performMiniaturize: + + + + 37 + + + + arrangeInFront: + + + + 39 + + + + print: + + + + 86 + + + + runPageLayout: + + + + 87 + + + + clearRecentDocuments: + + + + 127 + + + + orderFrontStandardAboutPanel: + + + + 142 + + + + performClose: + + + + 193 + + + + toggleContinuousSpellChecking: + + + + 222 + + + + undo: + + + + 223 + + + + copy: + + + + 224 + + + + checkSpelling: + + + + 225 + + + + paste: + + + + 226 + + + + stopSpeaking: + + + + 227 + + + + cut: + + + + 228 + + + + showGuessPanel: + + + + 230 + + + + redo: + + + + 231 + + + + selectAll: + + + + 232 + + + + startSpeaking: + + + + 233 + + + + delete: + + + + 235 + + + + performZoom: + + + + 240 + + + + performFindPanelAction: + + + + 241 + + + + centerSelectionInVisibleArea: + + + + 245 + + + + toggleGrammarChecking: + + + + 347 + + + + toggleSmartInsertDelete: + + + + 355 + + + + toggleAutomaticQuoteSubstitution: + + + + 356 + + + + toggleAutomaticLinkDetection: + + + + 357 + + + + saveDocument: + + + + 362 + + + + revertDocumentToSaved: + + + + 364 + + + + runToolbarCustomizationPalette: + + + + 365 + + + + toggleToolbarShown: + + + + 366 + + + + hide: + + + + 367 + + + + hideOtherApplications: + + + + 368 + + + + unhideAllApplications: + + + + 370 + + + + newDocument: + + + + 373 + + + + openDocument: + + + + 374 + + + + addFontTrait: + + + + 421 + + + + addFontTrait: + + + + 422 + + + + modifyFont: + + + + 423 + + + + orderFrontFontPanel: + + + + 424 + + + + modifyFont: + + + + 425 + + + + raiseBaseline: + + + + 426 + + + + lowerBaseline: + + + + 427 + + + + copyFont: + + + + 428 + + + + subscript: + + + + 429 + + + + superscript: + + + + 430 + + + + tightenKerning: + + + + 431 + + + + underline: + + + + 432 + + + + orderFrontColorPanel: + + + + 433 + + + + useAllLigatures: + + + + 434 + + + + loosenKerning: + + + + 435 + + + + pasteFont: + + + + 436 + + + + unscript: + + + + 437 + + + + useStandardKerning: + + + + 438 + + + + useStandardLigatures: + + + + 439 + + + + turnOffLigatures: + + + + 440 + + + + turnOffKerning: + + + + 441 + + + + terminate: + + + + 449 + + + + toggleAutomaticSpellingCorrection: + + + + 456 + + + + orderFrontSubstitutionsPanel: + + + + 458 + + + + toggleAutomaticDashSubstitution: + + + + 461 + + + + toggleAutomaticTextReplacement: + + + + 463 + + + + uppercaseWord: + + + + 464 + + + + capitalizeWord: + + + + 467 + + + + lowercaseWord: + + + + 468 + + + + pasteAsPlainText: + + + + 486 + + + + performFindPanelAction: + + + + 487 + + + + performFindPanelAction: + + + + 488 + + + + performFindPanelAction: + + + + 489 + + + + showHelp: + + + + 493 + + + + delegate + + + + 495 + + + + alignCenter: + + + + 518 + + + + pasteRuler: + + + + 519 + + + + toggleRuler: + + + + 520 + + + + alignRight: + + + + 521 + + + + copyRuler: + + + + 522 + + + + alignJustified: + + + + 523 + + + + alignLeft: + + + + 524 + + + + makeBaseWritingDirectionNatural: + + + + 525 + + + + makeBaseWritingDirectionLeftToRight: + + + + 526 + + + + makeBaseWritingDirectionRightToLeft: + + + + 527 + + + + makeTextWritingDirectionNatural: + + + + 528 + + + + makeTextWritingDirectionLeftToRight: + + + + 529 + + + + makeTextWritingDirectionRightToLeft: + + + + 530 + + + + window + + + + 532 + + + + performFindPanelAction: + + + + 535 + + + + + YES + + 0 + + YES + + + + + + -2 + + + File's Owner + + + -1 + + + First Responder + + + -3 + + + Application + + + 29 + + + YES + + + + + + + + + + + + 19 + + + YES + + + + + + 56 + + + YES + + + + + + 217 + + + YES + + + + + + 83 + + + YES + + + + + + 81 + + + YES + + + + + + + + + + + + + + + 75 + + + + + 78 + + + + + 72 + + + + + 82 + + + + + 124 + + + YES + + + + + + 77 + + + + + 73 + + + + + 79 + + + + + 112 + + + + + 74 + + + + + 125 + + + YES + + + + + + 126 + + + + + 205 + + + YES + + + + + + + + + + + + + + + + + + + + 202 + + + + + 198 + + + + + 207 + + + + + 214 + + + + + 199 + + + + + 203 + + + + + 197 + + + + + 206 + + + + + 215 + + + + + 218 + + + YES + + + + + + 216 + + + YES + + + + + + 200 + + + YES + + + + + + + + + + + 219 + + + + + 201 + + + + + 204 + + + + + 220 + + + YES + + + + + + + + + + + 213 + + + + + 210 + + + + + 221 + + + + + 208 + + + + + 209 + + + + + 57 + + + YES + + + + + + + + + + + + + + + + 58 + + + + + 134 + + + + + 150 + + + + + 136 + + + + + 144 + + + + + 129 + + + + + 143 + + + + + 236 + + + + + 131 + + + YES + + + + + + 149 + + + + + 145 + + + + + 130 + + + + + 24 + + + YES + + + + + + + + + 92 + + + + + 5 + + + + + 239 + + + + + 23 + + + + + 295 + + + YES + + + + + + 296 + + + YES + + + + + + + 297 + + + + + 298 + + + + + 211 + + + YES + + + + + + 212 + + + YES + + + + + + + 195 + + + + + 196 + + + + + 346 + + + + + 348 + + + YES + + + + + + 349 + + + YES + + + + + + + + + + + + 350 + + + + + 351 + + + + + 354 + + + + + 371 + + + YES + + + + + + 372 + + + + + 375 + + + YES + + + + + + 376 + + + YES + + + + + + + 377 + + + YES + + + + + + 388 + + + YES + + + + + + + + + + + + + + + + + + + + + 389 + + + + + 390 + + + + + 391 + + + + + 392 + + + + + 393 + + + + + 394 + + + + + 395 + + + + + 396 + + + + + 397 + + + YES + + + + + + 398 + + + YES + + + + + + 399 + + + YES + + + + + + 400 + + + + + 401 + + + + + 402 + + + + + 403 + + + + + 404 + + + + + 405 + + + YES + + + + + + + + + + 406 + + + + + 407 + + + + + 408 + + + + + 409 + + + + + 410 + + + + + 411 + + + YES + + + + + + + + 412 + + + + + 413 + + + + + 414 + + + + + 415 + + + YES + + + + + + + + + 416 + + + + + 417 + + + + + 418 + + + + + 419 + + + + + 420 + + + + + 450 + + + YES + + + + + + 451 + + + YES + + + + + + + + 452 + + + + + 453 + + + + + 454 + + + + + 457 + + + + + 459 + + + + + 460 + + + + + 462 + + + + + 465 + + + + + 466 + + + + + 485 + + + + + 490 + + + YES + + + + + + 491 + + + YES + + + + + + 492 + + + + + 494 + + + + + 496 + + + YES + + + + + + 497 + + + YES + + + + + + + + + + + + + + + 498 + + + + + 499 + + + + + 500 + + + + + 501 + + + + + 502 + + + + + 503 + + + YES + + + + + + 504 + + + + + 505 + + + + + 506 + + + + + 507 + + + + + 508 + + + YES + + + + + + + + + + + + + + 509 + + + + + 510 + + + + + 511 + + + + + 512 + + + + + 513 + + + + + 514 + + + + + 515 + + + + + 516 + + + + + 517 + + + + + 534 + + + + + + + YES + + YES + -1.IBPluginDependency + -2.IBPluginDependency + -3.IBPluginDependency + 112.IBPluginDependency + 112.ImportedFromIB2 + 124.IBPluginDependency + 124.ImportedFromIB2 + 125.IBPluginDependency + 125.ImportedFromIB2 + 125.editorWindowContentRectSynchronizationRect + 126.IBPluginDependency + 126.ImportedFromIB2 + 129.IBPluginDependency + 129.ImportedFromIB2 + 130.IBPluginDependency + 130.ImportedFromIB2 + 130.editorWindowContentRectSynchronizationRect + 131.IBPluginDependency + 131.ImportedFromIB2 + 134.IBPluginDependency + 134.ImportedFromIB2 + 136.IBPluginDependency + 136.ImportedFromIB2 + 143.IBPluginDependency + 143.ImportedFromIB2 + 144.IBPluginDependency + 144.ImportedFromIB2 + 145.IBPluginDependency + 145.ImportedFromIB2 + 149.IBPluginDependency + 149.ImportedFromIB2 + 150.IBPluginDependency + 150.ImportedFromIB2 + 19.IBPluginDependency + 19.ImportedFromIB2 + 195.IBPluginDependency + 195.ImportedFromIB2 + 196.IBPluginDependency + 196.ImportedFromIB2 + 197.IBPluginDependency + 197.ImportedFromIB2 + 198.IBPluginDependency + 198.ImportedFromIB2 + 199.IBPluginDependency + 199.ImportedFromIB2 + 200.IBEditorWindowLastContentRect + 200.IBPluginDependency + 200.ImportedFromIB2 + 200.editorWindowContentRectSynchronizationRect + 201.IBPluginDependency + 201.ImportedFromIB2 + 202.IBPluginDependency + 202.ImportedFromIB2 + 203.IBPluginDependency + 203.ImportedFromIB2 + 204.IBPluginDependency + 204.ImportedFromIB2 + 205.IBEditorWindowLastContentRect + 205.IBPluginDependency + 205.ImportedFromIB2 + 205.editorWindowContentRectSynchronizationRect + 206.IBPluginDependency + 206.ImportedFromIB2 + 207.IBPluginDependency + 207.ImportedFromIB2 + 208.IBPluginDependency + 208.ImportedFromIB2 + 209.IBPluginDependency + 209.ImportedFromIB2 + 210.IBPluginDependency + 210.ImportedFromIB2 + 211.IBPluginDependency + 211.ImportedFromIB2 + 212.IBPluginDependency + 212.ImportedFromIB2 + 212.editorWindowContentRectSynchronizationRect + 213.IBPluginDependency + 213.ImportedFromIB2 + 214.IBPluginDependency + 214.ImportedFromIB2 + 215.IBPluginDependency + 215.ImportedFromIB2 + 216.IBPluginDependency + 216.ImportedFromIB2 + 217.IBPluginDependency + 217.ImportedFromIB2 + 218.IBPluginDependency + 218.ImportedFromIB2 + 219.IBPluginDependency + 219.ImportedFromIB2 + 220.IBEditorWindowLastContentRect + 220.IBPluginDependency + 220.ImportedFromIB2 + 220.editorWindowContentRectSynchronizationRect + 221.IBPluginDependency + 221.ImportedFromIB2 + 23.IBPluginDependency + 23.ImportedFromIB2 + 236.IBPluginDependency + 236.ImportedFromIB2 + 239.IBPluginDependency + 239.ImportedFromIB2 + 24.IBEditorWindowLastContentRect + 24.IBPluginDependency + 24.ImportedFromIB2 + 24.editorWindowContentRectSynchronizationRect + 29.IBEditorWindowLastContentRect + 29.IBPluginDependency + 29.ImportedFromIB2 + 29.WindowOrigin + 29.editorWindowContentRectSynchronizationRect + 295.IBPluginDependency + 296.IBEditorWindowLastContentRect + 296.IBPluginDependency + 296.editorWindowContentRectSynchronizationRect + 297.IBPluginDependency + 298.IBPluginDependency + 346.IBPluginDependency + 346.ImportedFromIB2 + 348.IBPluginDependency + 348.ImportedFromIB2 + 349.IBEditorWindowLastContentRect + 349.IBPluginDependency + 349.ImportedFromIB2 + 349.editorWindowContentRectSynchronizationRect + 350.IBPluginDependency + 350.ImportedFromIB2 + 351.IBPluginDependency + 351.ImportedFromIB2 + 354.IBPluginDependency + 354.ImportedFromIB2 + 371.IBEditorWindowLastContentRect + 371.IBPluginDependency + 371.IBWindowTemplateEditedContentRect + 371.NSWindowTemplate.visibleAtLaunch + 371.editorWindowContentRectSynchronizationRect + 372.IBPluginDependency + 375.IBPluginDependency + 376.IBEditorWindowLastContentRect + 376.IBPluginDependency + 377.IBPluginDependency + 388.IBEditorWindowLastContentRect + 388.IBPluginDependency + 389.IBPluginDependency + 390.IBPluginDependency + 391.IBPluginDependency + 392.IBPluginDependency + 393.IBPluginDependency + 394.IBPluginDependency + 395.IBPluginDependency + 396.IBPluginDependency + 397.IBPluginDependency + 398.IBPluginDependency + 399.IBPluginDependency + 400.IBPluginDependency + 401.IBPluginDependency + 402.IBPluginDependency + 403.IBPluginDependency + 404.IBPluginDependency + 405.IBPluginDependency + 406.IBPluginDependency + 407.IBPluginDependency + 408.IBPluginDependency + 409.IBPluginDependency + 410.IBPluginDependency + 411.IBPluginDependency + 412.IBPluginDependency + 413.IBPluginDependency + 414.IBPluginDependency + 415.IBPluginDependency + 416.IBPluginDependency + 417.IBPluginDependency + 418.IBPluginDependency + 419.IBPluginDependency + 420.IBPluginDependency + 450.IBPluginDependency + 451.IBEditorWindowLastContentRect + 451.IBPluginDependency + 452.IBPluginDependency + 453.IBPluginDependency + 454.IBPluginDependency + 457.IBPluginDependency + 459.IBPluginDependency + 460.IBPluginDependency + 462.IBPluginDependency + 465.IBPluginDependency + 466.IBPluginDependency + 485.IBPluginDependency + 490.IBPluginDependency + 491.IBEditorWindowLastContentRect + 491.IBPluginDependency + 492.IBPluginDependency + 494.IBPluginDependency + 496.IBPluginDependency + 497.IBEditorWindowLastContentRect + 497.IBPluginDependency + 498.IBPluginDependency + 499.IBPluginDependency + 5.IBPluginDependency + 5.ImportedFromIB2 + 500.IBPluginDependency + 501.IBPluginDependency + 502.IBPluginDependency + 503.IBPluginDependency + 504.IBPluginDependency + 505.IBPluginDependency + 506.IBPluginDependency + 507.IBPluginDependency + 508.IBEditorWindowLastContentRect + 508.IBPluginDependency + 509.IBPluginDependency + 510.IBPluginDependency + 511.IBPluginDependency + 512.IBPluginDependency + 513.IBPluginDependency + 514.IBPluginDependency + 515.IBPluginDependency + 516.IBPluginDependency + 517.IBPluginDependency + 534.IBPluginDependency + 534.ImportedFromIB2 + 56.IBPluginDependency + 56.ImportedFromIB2 + 57.IBEditorWindowLastContentRect + 57.IBPluginDependency + 57.ImportedFromIB2 + 57.editorWindowContentRectSynchronizationRect + 58.IBPluginDependency + 58.ImportedFromIB2 + 72.IBPluginDependency + 72.ImportedFromIB2 + 73.IBPluginDependency + 73.ImportedFromIB2 + 74.IBPluginDependency + 74.ImportedFromIB2 + 75.IBPluginDependency + 75.ImportedFromIB2 + 77.IBPluginDependency + 77.ImportedFromIB2 + 78.IBPluginDependency + 78.ImportedFromIB2 + 79.IBPluginDependency + 79.ImportedFromIB2 + 81.IBEditorWindowLastContentRect + 81.IBPluginDependency + 81.ImportedFromIB2 + 81.editorWindowContentRectSynchronizationRect + 82.IBPluginDependency + 82.ImportedFromIB2 + 83.IBPluginDependency + 83.ImportedFromIB2 + 92.IBPluginDependency + 92.ImportedFromIB2 + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{522, 812}, {146, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{436, 809}, {64, 6}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{753, 187}, {275, 113}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {275, 83}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{547, 180}, {254, 283}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{187, 434}, {243, 243}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {167, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{753, 217}, {238, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {241, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{654, 239}, {194, 73}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{525, 802}, {197, 73}} + {{380, 836}, {512, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + + {74, 862} + {{6, 978}, {478, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + {{604, 269}, {231, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + {{475, 832}, {234, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{746, 287}, {220, 133}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {215, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{380, 496}, {480, 360}} + com.apple.InterfaceBuilder.CocoaPlugin + {{380, 496}, {480, 360}} + + {{33, 99}, {480, 360}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{591, 420}, {83, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{523, 2}, {178, 283}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{753, 197}, {170, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{725, 289}, {246, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{674, 260}, {204, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{878, 180}, {164, 173}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{286, 129}, {275, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{23, 794}, {245, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{452, 109}, {196, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{145, 474}, {199, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + + + + YES + + + + + + YES + + + + + 535 + + + + YES + + ABCardController + NSObject + + YES + + YES + addCardViewField: + copy: + cut: + doDelete: + find: + paste: + saveChanges: + + + YES + id + id + id + id + id + id + id + + + + YES + + YES + addCardViewField: + copy: + cut: + doDelete: + find: + paste: + saveChanges: + + + YES + + addCardViewField: + id + + + copy: + id + + + cut: + id + + + doDelete: + id + + + find: + id + + + paste: + id + + + saveChanges: + id + + + + + YES + + YES + mCardView + mEditButton + mManagedObjectContext + mSearchField + mStatusTextField + mWindow + + + YES + ABCardView + NSButton + NSManagedObjectContext + NSSearchField + NSTextField + NSWindow + + + + YES + + YES + mCardView + mEditButton + mManagedObjectContext + mSearchField + mStatusTextField + mWindow + + + YES + + mCardView + ABCardView + + + mEditButton + NSButton + + + mManagedObjectContext + NSManagedObjectContext + + + mSearchField + NSSearchField + + + mStatusTextField + NSTextField + + + mWindow + NSWindow + + + + + IBProjectSource + ./Classes/ABCardController.h + + + + ABCardView + NSView + + YES + + YES + commitAndSave: + statusImageClicked: + + + YES + id + id + + + + YES + + YES + commitAndSave: + statusImageClicked: + + + YES + + commitAndSave: + id + + + statusImageClicked: + id + + + + + YES + + YES + mBuddyStatusImage + mHeaderView + mNameView + mNextKeyView + mUserImage + mUserImageView + + + YES + NSImageView + NSView + ABNameFrameView + NSView + NSImage + ABImageView + + + + YES + + YES + mBuddyStatusImage + mHeaderView + mNameView + mNextKeyView + mUserImage + mUserImageView + + + YES + + mBuddyStatusImage + NSImageView + + + mHeaderView + NSView + + + mNameView + ABNameFrameView + + + mNextKeyView + NSView + + + mUserImage + NSImage + + + mUserImageView + ABImageView + + + + + IBProjectSource + ./Classes/ABCardView.h + + + + ABImageView + NSImageView + + YES + + YES + copy: + cut: + delete: + paste: + + + YES + id + id + id + id + + + + YES + + YES + copy: + cut: + delete: + paste: + + + YES + + copy: + id + + + cut: + id + + + delete: + id + + + paste: + id + + + + + IBProjectSource + ./Classes/ABImageView.h + + + + DVTAutoLayoutView + NSView + + IBProjectSource + ./Classes/DVTAutoLayoutView.h + + + + DVTBorderedView + DVTAutoLayoutView + + contentView + NSView + + + contentView + + contentView + NSView + + + + IBProjectSource + ./Classes/DVTBorderedView.h + + + + DVTDelayedMenuButton + NSButton + + IBProjectSource + ./Classes/DVTDelayedMenuButton.h + + + + DVTGradientImageButton + NSButton + + IBProjectSource + ./Classes/DVTGradientImageButton.h + + + + DVTImageAndTextCell + NSTextFieldCell + + IBProjectSource + ./Classes/DVTImageAndTextCell.h + + + + DVTImageAndTextColumn + NSTableColumn + + IBProjectSource + ./Classes/DVTImageAndTextColumn.h + + + + DVTOutlineView + NSOutlineView + + IBProjectSource + ./Classes/DVTOutlineView.h + + + + DVTSplitView + NSSplitView + + IBProjectSource + ./Classes/DVTSplitView.h + + + + DVTStackView + DVTAutoLayoutView + + IBProjectSource + ./Classes/DVTStackView.h + + + + DVTViewController + NSViewController + + IBProjectSource + ./Classes/DVTViewController.h + + + + HFController + NSObject + + selectAll: + id + + + selectAll: + + selectAll: + id + + + + IBProjectSource + ./Classes/HFController.h + + + + HFRepresenterTextView + NSView + + selectAll: + id + + + selectAll: + + selectAll: + id + + + + IBProjectSource + ./Classes/HFRepresenterTextView.h + + + + IBEditor + NSObject + + YES + + YES + changeFont: + selectAll: + sizeSelectionToFit: + + + YES + id + id + id + + + + YES + + YES + changeFont: + selectAll: + sizeSelectionToFit: + + + YES + + changeFont: + id + + + selectAll: + id + + + sizeSelectionToFit: + id + + + + + IBProjectSource + ./Classes/IBEditor.h + + + + IDECapsuleListView + DVTStackView + + dataSource + id + + + dataSource + + dataSource + id + + + + IBProjectSource + ./Classes/IDECapsuleListView.h + + + + IDEDMArrayController + NSArrayController + + IBProjectSource + ./Classes/IDEDMArrayController.h + + + + IDEDMEditor + IDEEditor + + YES + + YES + bottomToolbarBorderView + sourceListSplitViewPane + sourceListViewController + splitView + + + YES + DVTBorderedView + NSView + IDEDMEditorSourceListController + DVTSplitView + + + + YES + + YES + bottomToolbarBorderView + sourceListSplitViewPane + sourceListViewController + splitView + + + YES + + bottomToolbarBorderView + DVTBorderedView + + + sourceListSplitViewPane + NSView + + + sourceListViewController + IDEDMEditorSourceListController + + + splitView + DVTSplitView + + + + + IBProjectSource + ./Classes/IDEDMEditor.h + + + + IDEDMEditorController + IDEViewController + + IBProjectSource + ./Classes/IDEDMEditorController.h + + + + IDEDMEditorSourceListController + IDEDMEditorController + + YES + + YES + borderedView + parentEditor + primaryColumn + sourceListOutlineView + sourceListTreeController + + + YES + DVTBorderedView + IDEDMEditor + DVTImageAndTextColumn + DVTOutlineView + NSTreeController + + + + YES + + YES + borderedView + parentEditor + primaryColumn + sourceListOutlineView + sourceListTreeController + + + YES + + borderedView + DVTBorderedView + + + parentEditor + IDEDMEditor + + + primaryColumn + DVTImageAndTextColumn + + + sourceListOutlineView + DVTOutlineView + + + sourceListTreeController + NSTreeController + + + + + IBProjectSource + ./Classes/IDEDMEditorSourceListController.h + + + + IDEDMHighlightImageAndTextCell + DVTImageAndTextCell + + IBProjectSource + ./Classes/IDEDMHighlightImageAndTextCell.h + + + + IDEDataModelBrowserEditor + IDEDMEditorController + + YES + + YES + attributesTableViewController + capsuleView + entityArrayController + fetchedPropertiesTableViewController + parentEditor + relationshipsTableViewController + + + YES + IDEDataModelPropertiesTableController + IDECapsuleListView + NSArrayController + IDEDataModelPropertiesTableController + IDEDataModelEntityContentsEditor + IDEDataModelPropertiesTableController + + + + YES + + YES + attributesTableViewController + capsuleView + entityArrayController + fetchedPropertiesTableViewController + parentEditor + relationshipsTableViewController + + + YES + + attributesTableViewController + IDEDataModelPropertiesTableController + + + capsuleView + IDECapsuleListView + + + entityArrayController + NSArrayController + + + fetchedPropertiesTableViewController + IDEDataModelPropertiesTableController + + + parentEditor + IDEDataModelEntityContentsEditor + + + relationshipsTableViewController + IDEDataModelPropertiesTableController + + + + + IBProjectSource + ./Classes/IDEDataModelBrowserEditor.h + + + + IDEDataModelConfigurationEditor + IDEDMEditorController + + YES + + YES + capsuleListView + parentEditor + tableController + + + YES + IDECapsuleListView + IDEDataModelEditor + IDEDataModelConfigurationTableController + + + + YES + + YES + capsuleListView + parentEditor + tableController + + + YES + + capsuleListView + IDECapsuleListView + + + parentEditor + IDEDataModelEditor + + + tableController + IDEDataModelConfigurationTableController + + + + + IBProjectSource + ./Classes/IDEDataModelConfigurationEditor.h + + + + IDEDataModelConfigurationTableController + IDEDMEditorController + + YES + + YES + configurationsArrayController + entitiesArrayController + parentEditor + tableView + + + YES + NSArrayController + NSArrayController + IDEDataModelConfigurationEditor + XDTableView + + + + YES + + YES + configurationsArrayController + entitiesArrayController + parentEditor + tableView + + + YES + + configurationsArrayController + NSArrayController + + + entitiesArrayController + NSArrayController + + + parentEditor + IDEDataModelConfigurationEditor + + + tableView + XDTableView + + + + + IBProjectSource + ./Classes/IDEDataModelConfigurationTableController.h + + + + IDEDataModelDiagramEditor + IDEDMEditorController + + YES + + YES + diagramView + parentEditor + + + YES + XDDiagramView + IDEDataModelEntityContentsEditor + + + + YES + + YES + diagramView + parentEditor + + + YES + + diagramView + XDDiagramView + + + parentEditor + IDEDataModelEntityContentsEditor + + + + + IBProjectSource + ./Classes/IDEDataModelDiagramEditor.h + + + + IDEDataModelEditor + IDEDMEditor + + YES + + YES + addEntityButton + addPropertyButton + browserDiagramSegmentControl + configurationViewController + entityContentsViewController + fetchRequestViewController + hierarchySegmentControl + tabView + + + YES + DVTDelayedMenuButton + DVTDelayedMenuButton + NSSegmentedControl + IDEDataModelConfigurationEditor + IDEDataModelEntityContentsEditor + IDEDataModelFetchRequestEditor + NSSegmentedControl + NSTabView + + + + YES + + YES + addEntityButton + addPropertyButton + browserDiagramSegmentControl + configurationViewController + entityContentsViewController + fetchRequestViewController + hierarchySegmentControl + tabView + + + YES + + addEntityButton + DVTDelayedMenuButton + + + addPropertyButton + DVTDelayedMenuButton + + + browserDiagramSegmentControl + NSSegmentedControl + + + configurationViewController + IDEDataModelConfigurationEditor + + + entityContentsViewController + IDEDataModelEntityContentsEditor + + + fetchRequestViewController + IDEDataModelFetchRequestEditor + + + hierarchySegmentControl + NSSegmentedControl + + + tabView + NSTabView + + + + + IBProjectSource + ./Classes/IDEDataModelEditor.h + + + + IDEDataModelEntityContentsEditor + IDEDMEditorController + + YES + + YES + browserViewController + diagramViewController + parentEditor + tabView + + + YES + IDEDataModelBrowserEditor + IDEDataModelDiagramEditor + IDEDataModelEditor + NSTabView + + + + YES + + YES + browserViewController + diagramViewController + parentEditor + tabView + + + YES + + browserViewController + IDEDataModelBrowserEditor + + + diagramViewController + IDEDataModelDiagramEditor + + + parentEditor + IDEDataModelEditor + + + tabView + NSTabView + + + + + IBProjectSource + ./Classes/IDEDataModelEntityContentsEditor.h + + + + IDEDataModelFetchRequestEditor + IDEDMEditorController + + YES + + YES + entityController + parentEditor + tableView + + + YES + NSArrayController + IDEDataModelEditor + IDECapsuleListView + + + + YES + + YES + entityController + parentEditor + tableView + + + YES + + entityController + NSArrayController + + + parentEditor + IDEDataModelEditor + + + tableView + IDECapsuleListView + + + + + IBProjectSource + ./Classes/IDEDataModelFetchRequestEditor.h + + + + IDEDataModelPropertiesTableController + IDEDMEditorController + + YES + + YES + arrayController + entitiesColumn + entityArrayController + parentEditor + propertyNameAndImageCell + tableView + + + YES + IDEDMArrayController + NSTableColumn + NSArrayController + IDEDataModelBrowserEditor + IDEDMHighlightImageAndTextCell + XDTableView + + + + YES + + YES + arrayController + entitiesColumn + entityArrayController + parentEditor + propertyNameAndImageCell + tableView + + + YES + + arrayController + IDEDMArrayController + + + entitiesColumn + NSTableColumn + + + entityArrayController + NSArrayController + + + parentEditor + IDEDataModelBrowserEditor + + + propertyNameAndImageCell + IDEDMHighlightImageAndTextCell + + + tableView + XDTableView + + + + + IBProjectSource + ./Classes/IDEDataModelPropertiesTableController.h + + + + IDEDocSetOutlineView + NSOutlineView + + IBProjectSource + ./Classes/IDEDocSetOutlineView.h + + + + IDEDocSetOutlineViewController + NSObject + + YES + + YES + getDocSetAction: + showProblemInfoForUpdate: + subscribeToPublisherAction: + unsubscribeFromPublisher: + updateDocSetAction: + + + YES + id + id + id + id + id + + + + YES + + YES + getDocSetAction: + showProblemInfoForUpdate: + subscribeToPublisherAction: + unsubscribeFromPublisher: + updateDocSetAction: + + + YES + + getDocSetAction: + id + + + showProblemInfoForUpdate: + id + + + subscribeToPublisherAction: + id + + + unsubscribeFromPublisher: + id + + + updateDocSetAction: + id + + + + + docSetOutlineView + IDEDocSetOutlineView + + + docSetOutlineView + + docSetOutlineView + IDEDocSetOutlineView + + + + IBProjectSource + ./Classes/IDEDocSetOutlineViewController.h + + + + IDEDocViewingPrefPaneController + IDEViewController + + YES + + YES + addSubscription: + checkForAndInstallUpdatesNow: + minimumFontSizeComboBoxAction: + minimumFontSizeEnabledAction: + showHelp: + showSubscriptionSheet: + subscriptionCancelAction: + toggleAutoCheckForAndInstallUpdates: + toggleDocSetInfo: + + + YES + id + id + id + id + id + id + id + id + id + + + + YES + + YES + addSubscription: + checkForAndInstallUpdatesNow: + minimumFontSizeComboBoxAction: + minimumFontSizeEnabledAction: + showHelp: + showSubscriptionSheet: + subscriptionCancelAction: + toggleAutoCheckForAndInstallUpdates: + toggleDocSetInfo: + + + YES + + addSubscription: + id + + + checkForAndInstallUpdatesNow: + id + + + minimumFontSizeComboBoxAction: + id + + + minimumFontSizeEnabledAction: + id + + + showHelp: + id + + + showSubscriptionSheet: + id + + + subscriptionCancelAction: + id + + + toggleAutoCheckForAndInstallUpdates: + id + + + toggleDocSetInfo: + id + + + + + YES + + YES + _addButton + _deleteButton + _showInfoAreaButton + _splitView + _splitViewDocSetInfoSubview + _splitViewDocSetsListSubview + borderedViewAroundSplitView + borderedViewBelowTable + checkAndInstallNowButton + docSetInfoTextView + docSetOutlineViewController + minimumFontSizeControl + noUpdatesAvailableMessage + showInfoButton + subscriptionTextField + subscriptionWindow + validateAddSubscriptionButton + + + YES + DVTGradientImageButton + DVTGradientImageButton + DVTGradientImageButton + NSSplitView + NSView + NSView + DVTBorderedView + DVTBorderedView + NSButton + NSTextView + IDEDocSetOutlineViewController + NSComboBox + NSTextField + NSButton + NSTextField + NSWindow + NSButton + + + + YES + + YES + _addButton + _deleteButton + _showInfoAreaButton + _splitView + _splitViewDocSetInfoSubview + _splitViewDocSetsListSubview + borderedViewAroundSplitView + borderedViewBelowTable + checkAndInstallNowButton + docSetInfoTextView + docSetOutlineViewController + minimumFontSizeControl + noUpdatesAvailableMessage + showInfoButton + subscriptionTextField + subscriptionWindow + validateAddSubscriptionButton + + + YES + + _addButton + DVTGradientImageButton + + + _deleteButton + DVTGradientImageButton + + + _showInfoAreaButton + DVTGradientImageButton + + + _splitView + NSSplitView + + + _splitViewDocSetInfoSubview + NSView + + + _splitViewDocSetsListSubview + NSView + + + borderedViewAroundSplitView + DVTBorderedView + + + borderedViewBelowTable + DVTBorderedView + + + checkAndInstallNowButton + NSButton + + + docSetInfoTextView + NSTextView + + + docSetOutlineViewController + IDEDocSetOutlineViewController + + + minimumFontSizeControl + NSComboBox + + + noUpdatesAvailableMessage + NSTextField + + + showInfoButton + NSButton + + + subscriptionTextField + NSTextField + + + subscriptionWindow + NSWindow + + + validateAddSubscriptionButton + NSButton + + + + + IBProjectSource + ./Classes/IDEDocViewingPrefPaneController.h + + + + IDEEditor + IDEViewController + + IBProjectSource + ./Classes/IDEEditor.h + + + + IDEViewController + DVTViewController + + IBProjectSource + ./Classes/IDEViewController.h + + + + IKImageView + + YES + + YES + copy: + crop: + cut: + paste: + + + YES + id + id + id + id + + + + YES + + YES + copy: + crop: + cut: + paste: + + + YES + + copy: + id + + + crop: + id + + + cut: + id + + + paste: + id + + + + + IBProjectSource + ./Classes/IKImageView.h + + + + QTMovieView + + YES + + YES + showAll: + showCustomButton: + toggleLoops: + zoomIn: + zoomOut: + + + YES + id + id + id + id + id + + + + YES + + YES + showAll: + showCustomButton: + toggleLoops: + zoomIn: + zoomOut: + + + YES + + showAll: + id + + + showCustomButton: + id + + + toggleLoops: + id + + + zoomIn: + id + + + zoomOut: + id + + + + + IBProjectSource + ./Classes/QTMovieView.h + + + + WebView + + YES + + YES + reloadFromOrigin: + resetPageZoom: + zoomPageIn: + zoomPageOut: + + + YES + id + id + id + id + + + + YES + + YES + reloadFromOrigin: + resetPageZoom: + zoomPageIn: + zoomPageOut: + + + YES + + reloadFromOrigin: + id + + + resetPageZoom: + id + + + zoomPageIn: + id + + + zoomPageOut: + id + + + + + IBProjectSource + ./Classes/WebView.h + + + + XDDiagramView + NSView + + YES + + YES + _graphLayouterMenuItemAction: + _zoomPopUpButtonAction: + alignBottomEdges: + alignCentersHorizontallyInContainer: + alignCentersVerticallyInContainer: + alignHorizontalCenters: + alignLeftEdges: + alignRightEdges: + alignTopEdges: + alignVerticalCenters: + bringToFront: + collapseAllCompartments: + copy: + cut: + delete: + deleteBackward: + deleteForward: + deselectAll: + diagramZoomIn: + diagramZoomOut: + expandAllCompartments: + flipHorizontally: + flipVertically: + layoutGraphicsConcentrically: + layoutGraphicsHierarchically: + lock: + makeSameHeight: + makeSameWidth: + moveDown: + moveDownAndModifySelection: + moveLeft: + moveLeftAndModifySelection: + moveRight: + moveRightAndModifySelection: + moveUp: + moveUpAndModifySelection: + paste: + rollDownAllCompartments: + rollUpAllCompartments: + selectAll: + sendToBack: + sizeToFit: + toggleGridShown: + toggleHiddenGraphicsShown: + togglePageBreaksShown: + toggleRuler: + toggleSnapsToGrid: + unlock: + + + YES + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + id + + + + YES + + YES + _graphLayouterMenuItemAction: + _zoomPopUpButtonAction: + alignBottomEdges: + alignCentersHorizontallyInContainer: + alignCentersVerticallyInContainer: + alignHorizontalCenters: + alignLeftEdges: + alignRightEdges: + alignTopEdges: + alignVerticalCenters: + bringToFront: + collapseAllCompartments: + copy: + cut: + delete: + deleteBackward: + deleteForward: + deselectAll: + diagramZoomIn: + diagramZoomOut: + expandAllCompartments: + flipHorizontally: + flipVertically: + layoutGraphicsConcentrically: + layoutGraphicsHierarchically: + lock: + makeSameHeight: + makeSameWidth: + moveDown: + moveDownAndModifySelection: + moveLeft: + moveLeftAndModifySelection: + moveRight: + moveRightAndModifySelection: + moveUp: + moveUpAndModifySelection: + paste: + rollDownAllCompartments: + rollUpAllCompartments: + selectAll: + sendToBack: + sizeToFit: + toggleGridShown: + toggleHiddenGraphicsShown: + togglePageBreaksShown: + toggleRuler: + toggleSnapsToGrid: + unlock: + + + YES + + _graphLayouterMenuItemAction: + id + + + _zoomPopUpButtonAction: + id + + + alignBottomEdges: + id + + + alignCentersHorizontallyInContainer: + id + + + alignCentersVerticallyInContainer: + id + + + alignHorizontalCenters: + id + + + alignLeftEdges: + id + + + alignRightEdges: + id + + + alignTopEdges: + id + + + alignVerticalCenters: + id + + + bringToFront: + id + + + collapseAllCompartments: + id + + + copy: + id + + + cut: + id + + + delete: + id + + + deleteBackward: + id + + + deleteForward: + id + + + deselectAll: + id + + + diagramZoomIn: + id + + + diagramZoomOut: + id + + + expandAllCompartments: + id + + + flipHorizontally: + id + + + flipVertically: + id + + + layoutGraphicsConcentrically: + id + + + layoutGraphicsHierarchically: + id + + + lock: + id + + + makeSameHeight: + id + + + makeSameWidth: + id + + + moveDown: + id + + + moveDownAndModifySelection: + id + + + moveLeft: + id + + + moveLeftAndModifySelection: + id + + + moveRight: + id + + + moveRightAndModifySelection: + id + + + moveUp: + id + + + moveUpAndModifySelection: + id + + + paste: + id + + + rollDownAllCompartments: + id + + + rollUpAllCompartments: + id + + + selectAll: + id + + + sendToBack: + id + + + sizeToFit: + id + + + toggleGridShown: + id + + + toggleHiddenGraphicsShown: + id + + + togglePageBreaksShown: + id + + + toggleRuler: + id + + + toggleSnapsToGrid: + id + + + unlock: + id + + + + + _diagramController + IDEDataModelDiagramEditor + + + _diagramController + + _diagramController + IDEDataModelDiagramEditor + + + + IBProjectSource + ./Classes/XDDiagramView.h + + + + XDTableView + NSTableView + + showAllTableColumns: + id + + + showAllTableColumns: + + showAllTableColumns: + id + + + + IBProjectSource + ./Classes/XDTableView.h + + + + AFNetworking_Mac_ExampleAppDelegate + NSObject + + YES + + YES + applicationShouldTerminate: + applicationWillFinishLaunching: + + + YES + id + id + + + + YES + + YES + applicationShouldTerminate: + applicationWillFinishLaunching: + + + YES + + applicationShouldTerminate: + id + + + applicationWillFinishLaunching: + id + + + + + IBProjectSource + ./Classes/AFNetworking_Mac_ExampleAppDelegate.h + + + + + 0 + IBCocoaFramework + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 + + + YES + 3 + + YES + + YES + NSMenuCheckmark + NSMenuMixedState + + + YES + {9, 8} + {7, 2} + + + + diff --git a/Mac Example/AFNetworking Mac Example/main.m b/Mac Example/AFNetworking Mac Example/main.m new file mode 100644 index 0000000..4fd2746 --- /dev/null +++ b/Mac Example/AFNetworking Mac Example/main.m @@ -0,0 +1,14 @@ +// +// main.m +// AFNetworking Mac Example +// +// Created by Mattt Thompson on 11/09/23. +// Copyright 2011年 Gowalla. All rights reserved. +// + +#import + +int main(int argc, char *argv[]) +{ + return NSApplicationMain(argc, (const char **)argv); +} diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj similarity index 100% rename from Example/AFNetworking Example.xcodeproj/project.pbxproj rename to iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj diff --git a/Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist similarity index 100% rename from Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist rename to iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist diff --git a/Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme similarity index 100% rename from Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme rename to iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme diff --git a/Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist similarity index 100% rename from Example/AFNetworking Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist rename to iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist diff --git a/Example/AppDelegate.h b/iOS Example/AppDelegate.h similarity index 100% rename from Example/AppDelegate.h rename to iOS Example/AppDelegate.h diff --git a/Example/AppDelegate.m b/iOS Example/AppDelegate.m similarity index 100% rename from Example/AppDelegate.m rename to iOS Example/AppDelegate.m diff --git a/Example/Classes/AFGowallaAPIClient.h b/iOS Example/Classes/AFGowallaAPIClient.h similarity index 100% rename from Example/Classes/AFGowallaAPIClient.h rename to iOS Example/Classes/AFGowallaAPIClient.h diff --git a/Example/Classes/AFGowallaAPIClient.m b/iOS Example/Classes/AFGowallaAPIClient.m similarity index 100% rename from Example/Classes/AFGowallaAPIClient.m rename to iOS Example/Classes/AFGowallaAPIClient.m diff --git a/Example/Classes/Controllers/NearbySpotsViewController.h b/iOS Example/Classes/Controllers/NearbySpotsViewController.h similarity index 100% rename from Example/Classes/Controllers/NearbySpotsViewController.h rename to iOS Example/Classes/Controllers/NearbySpotsViewController.h diff --git a/Example/Classes/Controllers/NearbySpotsViewController.m b/iOS Example/Classes/Controllers/NearbySpotsViewController.m similarity index 100% rename from Example/Classes/Controllers/NearbySpotsViewController.m rename to iOS Example/Classes/Controllers/NearbySpotsViewController.m diff --git a/Example/Classes/Models/Spot.h b/iOS Example/Classes/Models/Spot.h similarity index 100% rename from Example/Classes/Models/Spot.h rename to iOS Example/Classes/Models/Spot.h diff --git a/Example/Classes/Models/Spot.m b/iOS Example/Classes/Models/Spot.m similarity index 100% rename from Example/Classes/Models/Spot.m rename to iOS Example/Classes/Models/Spot.m diff --git a/Example/Classes/Views/SpotTableViewCell.h b/iOS Example/Classes/Views/SpotTableViewCell.h similarity index 100% rename from Example/Classes/Views/SpotTableViewCell.h rename to iOS Example/Classes/Views/SpotTableViewCell.h diff --git a/Example/Classes/Views/SpotTableViewCell.m b/iOS Example/Classes/Views/SpotTableViewCell.m similarity index 100% rename from Example/Classes/Views/SpotTableViewCell.m rename to iOS Example/Classes/Views/SpotTableViewCell.m diff --git a/Example/Images/placeholder-stamp.png b/iOS Example/Images/placeholder-stamp.png similarity index 100% rename from Example/Images/placeholder-stamp.png rename to iOS Example/Images/placeholder-stamp.png diff --git a/Example/Images/placeholder-stamp@2x.png b/iOS Example/Images/placeholder-stamp@2x.png similarity index 100% rename from Example/Images/placeholder-stamp@2x.png rename to iOS Example/Images/placeholder-stamp@2x.png diff --git a/Example/Info.plist b/iOS Example/Info.plist similarity index 100% rename from Example/Info.plist rename to iOS Example/Info.plist diff --git a/Example/Prefix.pch b/iOS Example/Prefix.pch similarity index 100% rename from Example/Prefix.pch rename to iOS Example/Prefix.pch diff --git a/iOS Example/Vendor/JSONKit/JSONKit.h b/iOS Example/Vendor/JSONKit/JSONKit.h new file mode 100644 index 0000000..bdd5380 --- /dev/null +++ b/iOS Example/Vendor/JSONKit/JSONKit.h @@ -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 +#include +#include +#include +#include + +#ifdef __OBJC__ +#import +#import +#import +#import +#import +#import +#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 \ No newline at end of file diff --git a/iOS Example/Vendor/JSONKit/JSONKit.m b/iOS Example/Vendor/JSONKit/JSONKit.m new file mode 100644 index 0000000..3977849 --- /dev/null +++ b/iOS Example/Vendor/JSONKit/JSONKit.m @@ -0,0 +1,3011 @@ +// +// JSONKit.m +// 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. + */ + + +/* + Acknowledgments: + + The bulk of the UTF8 / UTF32 conversion and verification comes + from ConvertUTF.[hc]. It has been modified from the original sources. + + The original sources were obtained from http://www.unicode.org/. + However, the web site no longer seems to host the files. Instead, + the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4 + points to International Components for Unicode (ICU) + http://site.icu-project.org/ as an example of how to write a UTF + converter. + + The decision to use the ConvertUTF.[ch] code was made to leverage + "proven" code. Hopefully the local modifications are bug free. + + The code in isValidCodePoint() is derived from the ICU code in + utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR. + + From the original ConvertUTF.[ch]: + + * Copyright 2001-2004 Unicode, Inc. + * + * Disclaimer + * + * This source code is provided as is by Unicode, Inc. No claims are + * made as to fitness for any particular purpose. No warranties of any + * kind are expressed or implied. The recipient agrees to determine + * applicability of information provided. If this file has been + * purchased on magnetic or optical media from Unicode, Inc., the + * sole remedy for any claim will be exchange of defective media + * within 90 days of receipt. + * + * Limitations on Rights to Redistribute This Code + * + * Unicode, Inc. hereby grants the right to freely use the information + * supplied in this file in the creation of products supporting the + * Unicode Standard, and to make copies of this file in any form + * for internal or external distribution as long as this notice + * remains attached. + + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#import "JSONKit.h" + +//#include +#include +#include +#include +#include + +//#import +#import +#import +#import +#import +#import +#import +#import + +#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS +#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option. +#endif + +#ifdef __OBJC_GC__ +#error JSONKit does not support Objective-C Garbage Collection +#endif + +// The following checks are really nothing more than sanity checks. +// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety. +// In practice, though, for the compilers and architectures we can reasonably expect this code to be compiled for, these pedantic nitpicks aren't really a problem. +// Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be. + +#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL)) +#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively. +#endif + +#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT)) +#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures. +#endif + +// Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t + +#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type. +#endif + +#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX) +#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type. +#endif + + +// For DJB hash. +#define JK_HASH_INIT (1402737925UL) + +// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup. +#define JK_FAST_TRAILING_BYTES + +// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots. +#define JK_CACHE_SLOTS_BITS (10) +#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS) +// JK_CACHE_PROBES is the number of probe attempts. +#define JK_CACHE_PROBES (4UL) +// JK_INIT_CACHE_AGE must be (1 << AGE) - 1 +#define JK_INIT_CACHE_AGE (0) + +// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes) +#define JK_TOKENBUFFER_SIZE (1024UL * 2UL) + +// JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary. +#define JK_STACK_OBJS (1024UL * 1UL) + +#define JK_JSONBUFFER_SIZE (1024UL * 4UL) +#define JK_UTF8BUFFER_SIZE (1024UL * 16UL) + +#define JK_ENCODE_CACHE_SLOTS (1024UL) + + +#if defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) +#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) +#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U) +#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U) +#define JK_PREFETCH(ptr) __builtin_prefetch(ptr) +#else // defined (__GNUC__) && (__GNUC__ >= 4) +#define JK_ATTRIBUTES(attr, ...) +#define JK_EXPECTED(cond, expect) (cond) +#define JK_EXPECT_T(cond) (cond) +#define JK_EXPECT_F(cond) (cond) +#define JK_PREFETCH(ptr) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) + +#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline) +#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg)) +#define JK_UNUSED_ARG JK_ATTRIBUTES(unused) +#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result) +#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const) +#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure) +#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel) +#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) +#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) + +#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) +#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) +#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) +#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) + + +@class JKArray, JKDictionaryEnumerator, JKDictionary; + +enum { + JSONNumberStateStart = 0, + JSONNumberStateFinished = 1, + JSONNumberStateError = 2, + JSONNumberStateWholeNumberStart = 3, + JSONNumberStateWholeNumberMinus = 4, + JSONNumberStateWholeNumberZero = 5, + JSONNumberStateWholeNumber = 6, + JSONNumberStatePeriod = 7, + JSONNumberStateFractionalNumberStart = 8, + JSONNumberStateFractionalNumber = 9, + JSONNumberStateExponentStart = 10, + JSONNumberStateExponentPlusMinus = 11, + JSONNumberStateExponent = 12, +}; + +enum { + JSONStringStateStart = 0, + JSONStringStateParsing = 1, + JSONStringStateFinished = 2, + JSONStringStateError = 3, + JSONStringStateEscape = 4, + JSONStringStateEscapedUnicode1 = 5, + JSONStringStateEscapedUnicode2 = 6, + JSONStringStateEscapedUnicode3 = 7, + JSONStringStateEscapedUnicode4 = 8, + JSONStringStateEscapedUnicodeSurrogate1 = 9, + JSONStringStateEscapedUnicodeSurrogate2 = 10, + JSONStringStateEscapedUnicodeSurrogate3 = 11, + JSONStringStateEscapedUnicodeSurrogate4 = 12, + JSONStringStateEscapedNeedEscapeForSurrogate = 13, + JSONStringStateEscapedNeedEscapedUForSurrogate = 14, +}; + +enum { + JKParseAcceptValue = (1 << 0), + JKParseAcceptComma = (1 << 1), + JKParseAcceptEnd = (1 << 2), + JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd), + JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd), +}; + +enum { + JKClassUnknown = 0, + JKClassString = 1, + JKClassNumber = 2, + JKClassArray = 3, + JKClassDictionary = 4, + JKClassNull = 5, +}; + +enum { + JKManagedBufferOnStack = 1, + JKManagedBufferOnHeap = 2, + JKManagedBufferLocationMask = (0x3), + JKManagedBufferLocationShift = (0), + + JKManagedBufferMustFree = (1 << 2), +}; +typedef JKFlags JKManagedBufferFlags; + +enum { + JKObjectStackOnStack = 1, + JKObjectStackOnHeap = 2, + JKObjectStackLocationMask = (0x3), + JKObjectStackLocationShift = (0), + + JKObjectStackMustFree = (1 << 2), +}; +typedef JKFlags JKObjectStackFlags; + +enum { + JKTokenTypeInvalid = 0, + JKTokenTypeNumber = 1, + JKTokenTypeString = 2, + JKTokenTypeObjectBegin = 3, + JKTokenTypeObjectEnd = 4, + JKTokenTypeArrayBegin = 5, + JKTokenTypeArrayEnd = 6, + JKTokenTypeSeparator = 7, + JKTokenTypeComma = 8, + JKTokenTypeTrue = 9, + JKTokenTypeFalse = 10, + JKTokenTypeNull = 11, + JKTokenTypeWhiteSpace = 12, +}; +typedef NSUInteger JKTokenType; + +// These are prime numbers to assist with hash slot probing. +enum { + JKValueTypeNone = 0, + JKValueTypeString = 5, + JKValueTypeLongLong = 7, + JKValueTypeUnsignedLongLong = 11, + JKValueTypeDouble = 13, +}; +typedef NSUInteger JKValueType; + +enum { + JKEncodeOptionAsData = 1, + JKEncodeOptionAsString = 2, + JKEncodeOptionAsTypeMask = 0x7, + JKEncodeOptionCollectionObj = (1 << 3), + JKEncodeOptionStringObj = (1 << 4), + JKEncodeOptionStringObjTrimQuotes = (1 << 5), + +}; +typedef NSUInteger JKEncodeOptionType; + +typedef NSUInteger JKHash; + +typedef struct JKTokenCacheItem JKTokenCacheItem; +typedef struct JKTokenCache JKTokenCache; +typedef struct JKTokenValue JKTokenValue; +typedef struct JKParseToken JKParseToken; +typedef struct JKPtrRange JKPtrRange; +typedef struct JKObjectStack JKObjectStack; +typedef struct JKBuffer JKBuffer; +typedef struct JKConstBuffer JKConstBuffer; +typedef struct JKConstPtrRange JKConstPtrRange; +typedef struct JKRange JKRange; +typedef struct JKManagedBuffer JKManagedBuffer; +typedef struct JKFastClassLookup JKFastClassLookup; +typedef struct JKEncodeCache JKEncodeCache; +typedef struct JKEncodeState JKEncodeState; +typedef struct JKObjCImpCache JKObjCImpCache; +typedef struct JKHashTableEntry JKHashTableEntry; + +typedef id (*NSNumberAllocImp)(id receiver, SEL selector); +typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value); +typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object); +#ifdef __BLOCKS__ +typedef id (^JKClassFormatterBlock)(id formatObject); +#endif + + +struct JKPtrRange { + unsigned char *ptr; + size_t length; +}; + +struct JKConstPtrRange { + const unsigned char *ptr; + size_t length; +}; + +struct JKRange { + size_t location, length; +}; + +struct JKManagedBuffer { + JKPtrRange bytes; + JKManagedBufferFlags flags; + size_t roundSizeUpToMultipleOf; +}; + +struct JKObjectStack { + void **objects, **keys; + CFHashCode *cfHashes; + size_t count, index, roundSizeUpToMultipleOf; + JKObjectStackFlags flags; +}; + +struct JKBuffer { + JKPtrRange bytes; +}; + +struct JKConstBuffer { + JKConstPtrRange bytes; +}; + +struct JKTokenValue { + JKConstPtrRange ptrRange; + JKValueType type; + JKHash hash; + union { + long long longLongValue; + unsigned long long unsignedLongLongValue; + double doubleValue; + } number; + JKTokenCacheItem *cacheItem; +}; + +struct JKParseToken { + JKConstPtrRange tokenPtrRange; + JKTokenType type; + JKTokenValue value; + JKManagedBuffer tokenBuffer; +}; + +struct JKTokenCacheItem { + void *object; + JKHash hash; + CFHashCode cfHash; + size_t size; + unsigned char *bytes; + JKValueType type; +}; + +struct JKTokenCache { + JKTokenCacheItem *items; + size_t count; + unsigned int prng_lfsr; + unsigned char age[JK_CACHE_SLOTS]; +}; + +struct JKObjCImpCache { + Class NSNumberClass; + NSNumberAllocImp NSNumberAlloc; + NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong; +}; + +struct JKParseState { + JKParseOptionFlags parseOptionFlags; + JKConstBuffer stringBuffer; + size_t atIndex, lineNumber, lineStartIndex; + size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex; + JKParseToken token; + JKObjectStack objectStack; + JKTokenCache cache; + JKObjCImpCache objCImpCache; + NSError *error; + int errorIsPrev; + BOOL mutableCollections; +}; + +struct JKFastClassLookup { + void *stringClass; + void *numberClass; + void *arrayClass; + void *dictionaryClass; + void *nullClass; +}; + +struct JKEncodeCache { + id object; + size_t offset; + size_t length; +}; + +struct JKEncodeState { + JKManagedBuffer utf8ConversionBuffer; + JKManagedBuffer stringBuffer; + size_t atIndex; + JKFastClassLookup fastClassLookup; + JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS]; + JKSerializeOptionFlags serializeOptionFlags; + JKEncodeOptionType encodeOption; + size_t depth; + NSError *error; + id classFormatterDelegate; + SEL classFormatterSelector; + JKClassFormatterIMP classFormatterIMP; +#ifdef __BLOCKS__ + JKClassFormatterBlock classFormatterBlock; +#endif +}; + +// This is a JSONKit private class. +@interface JKSerializer : NSObject { + JKEncodeState *encodeState; +} + +#ifdef __BLOCKS__ +#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object) +#else +#define JKSERIALIZER_BLOCKS_PROTO id +#endif + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; +- (void)releaseState; + +@end + +struct JKHashTableEntry { + NSUInteger keyHash; + id key, object; +}; + + +typedef uint32_t UTF32; /* at least 32 bits */ +typedef uint16_t UTF16; /* at least 16 bits */ +typedef uint8_t UTF8; /* typically 8 bits */ + +typedef enum { + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD +#define UNI_MAX_BMP (UTF32)0x0000FFFF +#define UNI_MAX_UTF16 (UTF32)0x0010FFFF +#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF +#define UNI_SUR_HIGH_START (UTF32)0xD800 +#define UNI_SUR_HIGH_END (UTF32)0xDBFF +#define UNI_SUR_LOW_START (UTF32)0xDC00 +#define UNI_SUR_LOW_END (UTF32)0xDFFF + + +#if !defined(JK_FAST_TRAILING_BYTES) +static const char trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; +#endif + +static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; +static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + +#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex])) +#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length])) + + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection); +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex); +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject); +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex); + + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count); +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection); +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary); +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary); +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary); +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry); +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object); +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey); + + +static void _JSONDecoderCleanup(JSONDecoder *decoder); + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection); + + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer); +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length); +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize); +static void jk_objectStack_release(JKObjectStack *objectStack); +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count); +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount); + +static void jk_error(JKParseState *parseState, NSString *format, ...); +static int jk_parse_string(JKParseState *parseState); +static int jk_parse_number(JKParseState *parseState); +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr); +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState); +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState); +static int jk_parse_next_token(JKParseState *parseState); +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String); +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex); +static void *jk_parse_dictionary(JKParseState *parseState); +static void *jk_parse_array(JKParseState *parseState); +static void *jk_object_for_token(JKParseState *parseState); +static void *jk_cachedObjects(JKParseState *parseState); +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState); +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy); + + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...); +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...); +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format); +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState); +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format); +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format); +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length); +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr); +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object); +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr); + +#define jk_encode_write1(es, dc, f) (JK_EXPECT_F(_jk_encode_prettyPrint) ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b); +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b); +JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c); + +// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type. +// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the +// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection +// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable. +// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4. + +#pragma mark - +@interface JKArray : NSMutableArray { + id *objects; + NSUInteger count, capacity, mutations; +} +@end + +@implementation JKArray + +static Class _JKArrayClass = NULL; +static size_t _JKArrayInstanceSize = 0UL; + ++ (void)load +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal. + + _JKArrayClass = objc_getClass("JKArray"); + _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass)); + + [pool release]; pool = NULL; +} + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL)); + JKArray *array = NULL; + if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc. + array->isa = _JKArrayClass; + if((array = [array init]) == NULL) { return(NULL); } + array->capacity = count; + array->count = count; + if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); } + memcpy(array->objects, objects, array->capacity * sizeof(id)); + array->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(array); +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; } + array->count++; + if(array->count >= array->capacity) { + array->capacity += 16UL; + id *newObjects = NULL; + if((newObjects = (id *)realloc(array->objects, sizeof(id) * array->capacity)) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; } + array->objects = newObjects; + memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count)); + } + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; } + array->objects[objectIndex] = newObject; +} + +// Note: The caller is responsible for -retaining the object that is to be added. +static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + array->objects[objectIndex] = newObject; +} + +static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) { + NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL)); + if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; } + CFRelease(array->objects[objectIndex]); + array->objects[objectIndex] = NULL; + if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count] = NULL; } + array->count--; +} + +- (void)dealloc +{ + if(JK_EXPECT_T(objects != NULL)) { + NSUInteger atObject = 0UL; + for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } } + free(objects); objects = NULL; + } + + [super dealloc]; +} + +- (NSUInteger)count +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return(count); +} + +- (void)getObjects:(id *)objectsPtr range:(NSRange)range +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range)]; } + if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; } + memcpy(objectsPtr, objects + range.location, range.length * sizeof(id)); +} + +- (id)objectAtIndex:(NSUInteger)objectIndex +{ + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL)); + return(objects[objectIndex]); +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= count)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; } + + return(enumeratedCount); +} + +- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count + 1UL]; } + anObject = [anObject retain]; + _JKArrayInsertObjectAtIndex(self, anObject, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectAtIndex:(NSUInteger)objectIndex +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + _JKArrayRemoveObjectAtIndex(self, objectIndex); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + anObject = [anObject retain]; + _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [[NSArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((objects != NULL) && (count <= capacity)); + return([[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]); +} + +@end + + +#pragma mark - +@interface JKDictionaryEnumerator : NSEnumerator { + id collection; + NSUInteger nextObject; +} + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary; +- (NSArray *)allObjects; +- (id)nextObject; + +@end + +@implementation JKDictionaryEnumerator + +- (id)initWithJKDictionary:(JKDictionary *)initDictionary +{ + NSParameterAssert(initDictionary != NULL); + if((self = [super init]) == NULL) { return(NULL); } + if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); } + return(self); +} + +- (void)dealloc +{ + if(collection != NULL) { CFRelease(collection); collection = NULL; } + [super dealloc]; +} + +- (NSArray *)allObjects +{ + NSParameterAssert(collection != NULL); + NSUInteger count = [collection count], atObject = 0UL; + id objects[count]; + + while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; } + + return([NSArray arrayWithObjects:objects count:atObject]); +} + +- (id)nextObject +{ + NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL)); + JKHashTableEntry *entry = _JKDictionaryHashEntry(collection); + NSUInteger capacity = _JKDictionaryCapacity(collection); + id returnObject = NULL; + + if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } } + + return(returnObject); +} + +@end + +#pragma mark - +@interface JKDictionary : NSMutableDictionary { + NSUInteger count, capacity, mutations; + JKHashTableEntry *entry; +} +@end + +@implementation JKDictionary + +static Class _JKDictionaryClass = NULL; +static size_t _JKDictionaryInstanceSize = 0UL; + ++ (void)load +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal. + + _JKDictionaryClass = objc_getClass("JKDictionary"); + _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass)); + + [pool release]; pool = NULL; +} + ++ (id)allocWithZone:(NSZone *)zone +{ +#pragma unused(zone) + [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; + return(NULL); +} + +// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too. +static const NSUInteger jk_dictionaryCapacities[] = { + 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL, + 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL, + 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL, + 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL, + 111638519UL, 180634607UL, 292272623UL, 472907251UL +}; + +static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) { + NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33)); + while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } } + return(jk_dictionaryCapacities[bottom]); +} + +static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + + NSUInteger capacityForCount = 0UL; + if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize + NSUInteger oldCapacity = dictionary->capacity; +#ifndef NS_BLOCK_ASSERTIONS + NSUInteger oldCount = dictionary->count; +#endif + JKHashTableEntry *oldEntry = dictionary->entry; + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; } + dictionary->capacity = capacityForCount; + dictionary->count = 0UL; + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < oldCapacity; idx++) { if(oldEntry[idx].key != NULL) { _JKDictionaryAddObject(dictionary, oldEntry[idx].keyHash, oldEntry[idx].key, oldEntry[idx].object); oldEntry[idx].keyHash = 0UL; oldEntry[idx].key = NULL; oldEntry[idx].object = NULL; } } + NSCParameterAssert((oldCount == dictionary->count)); + free(oldEntry); oldEntry = NULL; + } +} + +static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) { + NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL)); + JKDictionary *dictionary = NULL; + if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc. + dictionary->isa = _JKDictionaryClass; + if((dictionary = [dictionary init]) == NULL) { return(NULL); } + dictionary->capacity = _JKDictionaryCapacityForCount(count); + dictionary->count = 0UL; + + if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); } + + NSUInteger idx = 0UL; + for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); } + + dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL; + } + return(dictionary); +} + +- (void)dealloc +{ + if(JK_EXPECT_T(entry != NULL)) { + NSUInteger atEntry = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; } + if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; } + } + + free(entry); entry = NULL; + } + + [super dealloc]; +} + +static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->entry); +} + +static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) { + NSCParameterAssert(dictionary != NULL); + return(dictionary->capacity); +} + +static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) { + NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity)); + CFRelease(entry->key); entry->key = NULL; + CFRelease(entry->object); entry->object = NULL; + entry->keyHash = 0UL; + dictionary->count--; + // In order for certain invariants that are used to speed up the search for a particular key, we need to "re-add" all the entries in the hash table following this entry until we hit a NULL entry. + NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL; + NSCParameterAssert((removeIdx < dictionary->capacity)); + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(atEntry->key == NULL) { break; } + NSUInteger keyHash = atEntry->keyHash; + id key = atEntry->key, object = atEntry->object; + NSCParameterAssert(object != NULL); + atEntry->keyHash = 0UL; + atEntry->key = NULL; + atEntry->object = NULL; + NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL; + for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) { + JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)]; + if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; } + } + } +} + +static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) { + NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL)); + NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity; + JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; + if(JK_EXPECT_F(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && (JK_EXPECT_F(key == atEntry->key) || JK_EXPECT_F(CFEqual(atEntry->key, key)))) { _JKDictionaryRemoveObjectWithEntry(dictionary, atEntry); } + if(JK_EXPECT_T(atEntry->key == NULL)) { NSCParameterAssert((atEntry->keyHash == 0UL) && (atEntry->object == NULL)); atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; } + } + + // We should never get here. If we do, we -release the key / object because it's our responsibility. + CFRelease(key); + CFRelease(object); +} + +- (NSUInteger)count +{ + return(count); +} + +static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) { + NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); + if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); } + NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL; + JKHashTableEntry *atEntry = NULL; + for(idx = 0UL; idx < dictionary->capacity; idx++) { + atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity]; + if(JK_EXPECT_T(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && ((atEntry->key == aKey) || CFEqual(atEntry->key, aKey))) { NSCParameterAssert(atEntry->object != NULL); return(atEntry); break; } + if(JK_EXPECT_F(atEntry->key == NULL)) { NSCParameterAssert(atEntry->object == NULL); return(NULL); break; } // If the key was in the table, we would have found it by now. + } + return(NULL); +} + +- (id)objectForKey:(id)aKey +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + return((entryForKey != NULL) ? entryForKey->object : NULL); +} + +- (void)getObjects:(id *)objects andKeys:(id *)keys +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL; + for(atEntry = 0UL; atEntry < capacity; atEntry++) { + if(JK_EXPECT_T(entry[atEntry].key != NULL)) { + NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count)); + if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; } + if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; } + arrayIdx++; + } + } +} + +- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len +{ + NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity)); + if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } + if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); } + + NSUInteger enumeratedCount = 0UL; + while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < capacity)) { if(JK_EXPECT_T(entry[state->state].key != NULL)) { stackbuf[enumeratedCount++] = entry[state->state].key; } state->state++; } + + return(enumeratedCount); +} + +- (NSEnumerator *)keyEnumerator +{ + return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]); +} + +- (void)setObject:(id)anObject forKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; } + + _JKDictionaryResizeIfNeccessary(self); +#ifndef __clang_analyzer__ + aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak", + anObject = [anObject retain]; // but this -retain doesn't!? +#endif // __clang_analyzer__ + _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; +} + +- (void)removeObjectForKey:(id)aKey +{ + if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } + JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); + if(entryForKey != NULL) { + _JKDictionaryRemoveObjectWithEntry(self, entryForKey); + mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; + } +} + +- (id)copyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]); +} + +- (id)mutableCopyWithZone:(NSZone *)zone +{ + NSParameterAssert((entry != NULL) && (count <= capacity)); + return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]); +} + +@end + + + +#pragma mark - + +JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); } +JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); } + +JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); } + +static void jk_error(JKParseState *parseState, NSString *format, ...) { + NSCParameterAssert((parseState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + +#if 0 + const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex; + const unsigned char *lineEnd = lineStart; + const unsigned char *atCharacterPtr = NULL; + + for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } } + + NSString *lineString = @"", *carretString = @""; + if(lineStart < JK_END_STRING_PTR(parseState)) { + lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease]; + carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "]; + } +#endif + + if(parseState->error == NULL) { + parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey", + [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey", + //lineString, @"JKErrorLine0Key", + //carretString, @"JKErrorLine1Key", + NULL]]; + } +} + +#pragma mark - +#pragma mark Buffer and Object Stack management functions + +static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) { + if((managedBuffer->flags & JKManagedBufferMustFree)) { + if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; } + managedBuffer->flags &= ~JKManagedBufferMustFree; + } + + managedBuffer->bytes.ptr = NULL; + managedBuffer->bytes.length = 0UL; + managedBuffer->flags &= ~JKManagedBufferLocationMask; +} + +static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) { + jk_managedBuffer_release(managedBuffer); + managedBuffer->bytes.ptr = ptr; + managedBuffer->bytes.length = length; + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack; +} + +static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) { + size_t roundedUpNewSize = newSize; + + if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); } + + if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) { + if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) { + NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0); + unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr; + + if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); } + memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize)); + managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree); + managedBuffer->bytes.ptr = newBuffer; + managedBuffer->bytes.length = roundedUpNewSize; + } else { + NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap)); + if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); } + managedBuffer->bytes.length = roundedUpNewSize; + } + } + + return(managedBuffer->bytes.ptr); +} + + + +static void jk_objectStack_release(JKObjectStack *objectStack) { + NSCParameterAssert(objectStack != NULL); + + NSCParameterAssert(objectStack->index <= objectStack->count); + size_t atIndex = 0UL; + for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) { + if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; } + if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; } + } + objectStack->index = 0UL; + + if(objectStack->flags & JKObjectStackMustFree) { + NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap); + if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; } + if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; } + if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; } + objectStack->flags &= ~JKObjectStackMustFree; + } + + objectStack->objects = NULL; + objectStack->keys = NULL; + objectStack->cfHashes = NULL; + + objectStack->count = 0UL; + objectStack->flags &= ~JKObjectStackLocationMask; +} + +static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) { + NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL)); + jk_objectStack_release(objectStack); + objectStack->objects = objects; + objectStack->keys = keys; + objectStack->cfHashes = cfHashes; + objectStack->count = count; + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack; +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif +} + +static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) { + size_t roundedUpNewCount = newCount; + int returnCode = 0; + + void **newObjects = NULL, **newKeys = NULL; + CFHashCode *newCFHashes = NULL; + + if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); } + + if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) { + if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) { + NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0); + + if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); + + if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; } + memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode)); + + objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree); + objectStack->objects = newObjects; newObjects = NULL; + objectStack->keys = newKeys; newKeys = NULL; + objectStack->cfHashes = newCFHashes; newCFHashes = NULL; + objectStack->count = roundedUpNewCount; + } else { + NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap)); + if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; } + if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; } + if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; } + +#ifndef NS_BLOCK_ASSERTIONS + size_t idx; + for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } +#endif + objectStack->count = roundedUpNewCount; + } + } + +errorExit: + if(newObjects != NULL) { free(newObjects); newObjects = NULL; } + if(newKeys != NULL) { free(newKeys); newKeys = NULL; } + if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; } + + return(returnCode); +} + +//////////// +#pragma mark - +#pragma mark Unicode related functions + +JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) { + ConversionResult result = conversionOK; + UTF32 ch = *u32CodePoint; + + if(JK_EXPECT_F(ch >= UNI_SUR_HIGH_START) && (JK_EXPECT_T(ch <= UNI_SUR_LOW_END))) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch >= 0xFDD0U) && (JK_EXPECT_F(ch <= 0xFDEFU) || JK_EXPECT_F((ch & 0xFFFEU) == 0xFFFEU)) && JK_EXPECT_T(ch <= 0x10FFFFU)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } + +finished: + *u32CodePoint = ch; + return(result); +} + + +static int isLegalUTF8(const UTF8 *source, size_t length) { + const UTF8 *srcptr = source + length; + UTF8 a; + + switch(length) { + default: return(0); // Everything else falls through when "true"... + case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } + case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); } + + switch(*source) { // no fall-through in this inner switch + case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break; + case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break; + case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break; + case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break; + default: if(JK_EXPECT_F(a < 0x80)) { return(0); } + } + + case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); } + } + + if(JK_EXPECT_F(*source > 0xF4)) { return(0); } + + return(1); +} + +static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) { + ConversionResult result = conversionOK; + const UTF8 *source = sourceStart; + UTF32 ch = 0UL; + +#if !defined(JK_FAST_TRAILING_BYTES) + unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; +#else + unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25); +#endif + + if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) { + source++; + while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; } + NSCParameterAssert(source <= sourceEnd); + result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal; + ch = UNI_REPLACEMENT_CHAR; + goto finished; + } + + switch(extraBytesToRead) { // The cases all fall through. + case 5: ch += *source++; ch <<= 6; + case 4: ch += *source++; ch <<= 6; + case 3: ch += *source++; ch <<= 6; + case 2: ch += *source++; ch <<= 6; + case 1: ch += *source++; ch <<= 6; + case 0: ch += *source++; + } + ch -= offsetsFromUTF8[extraBytesToRead]; + + result = isValidCodePoint(&ch); + +finished: + *nextUTF8 = source; + *convertedUTF32 = ch; + + return(result); +} + + +static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) { + const UTF32 byteMask = 0xBF, byteMark = 0x80; + ConversionResult result = conversionOK; + UTF8 *target = *targetStart; + UTF32 ch = u32CodePoint; + unsigned short bytesToWrite = 0; + + result = isValidCodePoint(&ch); + + // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars. + if(ch < (UTF32)0x80) { bytesToWrite = 1; } + else if(ch < (UTF32)0x800) { bytesToWrite = 2; } + else if(ch < (UTF32)0x10000) { bytesToWrite = 3; } + else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } + else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } + + target += bytesToWrite; + if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; } + + switch (bytesToWrite) { // note: everything falls through. + case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; + case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); + } + + target += bytesToWrite; + +finished: + *targetStart = target; + return(result); +} + +JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) { + UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx]; + ConversionResult result; + + if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } } + size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len; + + while(*tokenBufferIdx < nextIdx) { *stringHash = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } + + return(0); +} + +//////////// +#pragma mark - +#pragma mark Decoding / parsing / deserializing functions + +static int jk_parse_string(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1; + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atStringCharacter = stringStart; + unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr; + size_t tokenStartIndex = parseState->atIndex; + size_t tokenBufferIdx = 0UL; + + int onlySimpleString = 1, stringState = JSONStringStateStart; + uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U; + uint32_t escapedUnicodeCodePoint = 0U; + JKHash stringHash = JK_HASH_INIT; + + while(1) { + unsigned long currentChar; + + if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; } + + if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; } + stringHash = calculateHash(stringHash, currentChar); + while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = calculateHash(stringHash, *atStringCharacter++); } + continue; + } else { + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; } + + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { + switchToSlowPath: + onlySimpleString = 0; + stringState = JSONStringStateParsing; + tokenBufferIdx = (atStringCharacter - stringStart) - 1L; + if(JK_EXPECT_F((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length)) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + memcpy(tokenBuffer, stringStart, tokenBufferIdx); + goto slowMatch; + } + + if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } + + stringHash = calculateHash(stringHash, currentChar); + } + } + +slowMatch: + + for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) { + if((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + + NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); + + unsigned long currentChar = (*atStringCharacter), escapedChar; + + if(JK_EXPECT_T(stringState == JSONStringStateParsing)) { + if(JK_EXPECT_T(currentChar >= 0x20UL)) { + if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence + if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; } + if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; } + stringHash = calculateHash(stringHash, currentChar); + tokenBuffer[tokenBufferIdx++] = currentChar; + continue; + } else { // UTF8 sequence + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { + if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } + if(jk_string_add_unicodeCodePoint(parseState, u32ch, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + atStringCharacter = nextValidCharacter - 1; + continue; + } else { + while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); } + atStringCharacter--; + continue; + } + } + } else { // currentChar < 0x20 + jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; + } + + } else { // stringState != JSONStringStateParsing + int isSurrogate = 1; + + switch(stringState) { + case JSONStringStateEscape: + switch(currentChar) { + case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break; + + case 'b': escapedChar = '\b'; goto parsedEscapedChar; + case 'f': escapedChar = '\f'; goto parsedEscapedChar; + case 'n': escapedChar = '\n'; goto parsedEscapedChar; + case 'r': escapedChar = '\r'; goto parsedEscapedChar; + case 't': escapedChar = '\t'; goto parsedEscapedChar; + case '\\': escapedChar = '\\'; goto parsedEscapedChar; + case '/': escapedChar = '/'; goto parsedEscapedChar; + case '"': escapedChar = '"'; goto parsedEscapedChar; + + parsedEscapedChar: + stringState = JSONStringStateParsing; + stringHash = calculateHash(stringHash, escapedChar); + tokenBuffer[tokenBufferIdx++] = escapedChar; + break; + + default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break; + } + break; + + case JSONStringStateEscapedUnicode1: + case JSONStringStateEscapedUnicode2: + case JSONStringStateEscapedUnicode3: + case JSONStringStateEscapedUnicode4: isSurrogate = 0; + case JSONStringStateEscapedUnicodeSurrogate1: + case JSONStringStateEscapedUnicodeSurrogate2: + case JSONStringStateEscapedUnicodeSurrogate3: + case JSONStringStateEscapedUnicodeSurrogate4: + { + uint16_t hexValue = 0U; + + switch(currentChar) { + case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex; + case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex; + case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex; + + parsedHex: + if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; } + + if(stringState == JSONStringStateEscapedUnicode4) { + if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) { + if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; } + else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + } + else { escapedUnicodeCodePoint = escapedUnicode1; } + } + + if(stringState == JSONStringStateEscapedUnicodeSurrogate4) { + if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } + else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + } + else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; } + } + + if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) { + if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + stringState = JSONStringStateParsing; + if(jk_string_add_unicodeCodePoint(parseState, escapedUnicodeCodePoint, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } + } + else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; } + break; + + default: jk_error(parseState, @"Unexpected character found in \\u Unicode escape sequence. Found '%c', expected [0-9a-fA-F].", currentChar); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + break; + + case JSONStringStateEscapedNeedEscapeForSurrogate: + if((currentChar == '\\')) { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter--; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + case JSONStringStateEscapedNeedEscapedUForSurrogate: + if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; } + else { + if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } + else { stringState = JSONStringStateParsing; atStringCharacter -= 2; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } + } + break; + + default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break; + } + } + } + +finishedParsing: + + if(JK_EXPECT_T(stringState == JSONStringStateFinished)) { + NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter); + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex; + parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr); + + if(JK_EXPECT_T(onlySimpleString)) { + NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer)); + parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1; + parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL; + } else { + parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr; + parseState->token.value.ptrRange.length = tokenBufferIdx; + } + + parseState->token.value.hash = stringHash; + parseState->token.value.type = JKValueTypeString; + parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr); + } + + if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); } + return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1); +} + +static int jk_parse_number(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *numberStart = JK_AT_STRING_PTR(parseState); + const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); + const unsigned char *atNumberCharacter = NULL; + int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0; + size_t startingIndex = parseState->atIndex; + + for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) { + unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL; + + switch(numberState) { + case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; } + case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; } + else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; } + else { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; } + case JSONNumberStateFractionalNumberStart: + case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; } + else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; } + else { numberState = JSONNumberStateExponent; } break; } + case JSONNumberStateWholeNumberZero: + case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; } + case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; } + case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; } + break; + default: /* XXX Add error message */ numberState = JSONNumberStateError; break; + } + } + + parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex; + parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup; + parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr; + + if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) { + unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL]; + unsigned char *endOfNumber = NULL; + + memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length); + numberTempBuf[parseState->token.tokenPtrRange.length] = 0; + + errno = 0; + + // Treat "-0" as a floating point number, which is capable of representing negative zeros. + if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; } + + if(isFloatingPoint) { + parseState->token.value.number.doubleValue = strtod((const char *)numberTempBuf, (char **)&endOfNumber); // strtod is documented to return U+2261 (identical to) 0.0 on an underflow error (along with setting errno to ERANGE). + parseState->token.value.type = JKValueTypeDouble; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue; + parseState->token.value.ptrRange.length = sizeof(double); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type); + } else { + if(isNegative) { + parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue; + parseState->token.value.ptrRange.length = sizeof(long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue; + } else { + parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10); + parseState->token.value.type = JKValueTypeUnsignedLongLong; + parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue; + parseState->token.value.ptrRange.length = sizeof(unsigned long long); + parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue; + } + } + + if(JK_EXPECT_F(errno != 0)) { + numberState = JSONNumberStateError; + if(errno == ERANGE) { + switch(parseState->token.value.type) { + case JKValueTypeDouble: jk_error(parseState, @"The value '%s' could not be represented as a 'double' due to %s.", numberTempBuf, (parseState->token.value.number.doubleValue == 0.0) ? "underflow" : "overflow"); break; // see above for == 0.0. + case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + } + } + if(JK_EXPECT_F(endOfNumber != &numberTempBuf[parseState->token.tokenPtrRange.length]) && JK_EXPECT_F(numberState != JSONNumberStateError)) { numberState = JSONNumberStateError; jk_error(parseState, @"The conversion function did not consume all of the number tokens characters."); } + + size_t hashIndex = 0UL; + for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } + } + + if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); } + return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1); +} + +JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) { + parseState->token.tokenPtrRange.ptr = ptr; + parseState->token.tokenPtrRange.length = length; + parseState->token.type = type; + parseState->atIndex += advanceBy; +} + +static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) { + NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState))); + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); } + + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); } + if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); } + if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); } + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); } + } + + return(0UL); +} + +JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) { + size_t newlineAdvanceAtIndex = 0UL; + if(JK_EXPECT_F((newlineAdvanceAtIndex = jk_parse_is_newline(parseState, JK_AT_STRING_PTR(parseState))) > 0UL)) { parseState->lineNumber++; parseState->atIndex += (newlineAdvanceAtIndex - 1UL); parseState->lineStartIndex = parseState->atIndex + 1UL; return(1); } + return(0); +} + +JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) { +#ifndef __clang_analyzer__ + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; } + if(jk_parse_skip_newline(parseState)) { continue; } + if(parseState->parseOptionFlags & JKParseOptionComments) { + if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) { + if((*(atCharacterPtr + 1)) == '/') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { break; } } + continue; + } + if((*(atCharacterPtr + 1)) == '*') { + parseState->atIndex++; + for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { + if(jk_parse_skip_newline(parseState)) { continue; } + if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; } + } + continue; + } + } + } + break; + } +#endif +} + +static int jk_parse_next_token(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + const unsigned char *atCharacterPtr = NULL; + const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); + unsigned char currentCharacter = 0U; + int stopParsing = 0; + + parseState->prev_atIndex = parseState->atIndex; + parseState->prev_lineNumber = parseState->lineNumber; + parseState->prev_lineStartIndex = parseState->lineStartIndex; + + jk_parse_skip_whitespace(parseState); + + if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) { + currentCharacter = *atCharacterPtr; + + if(JK_EXPECT_T(currentCharacter == '"')) { if(JK_EXPECT_T((stopParsing = jk_parse_string(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeString, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); } + else if((JK_EXPECT_T(currentCharacter >= '0') && JK_EXPECT_T(currentCharacter <= '9')) || JK_EXPECT_T(currentCharacter == '-')) { if(JK_EXPECT_T((stopParsing = jk_parse_number(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeNumber, 0UL); } } + else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); } + else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); } + else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); } + + else if(JK_EXPECT_T(currentCharacter == 't')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'r')) && (JK_EXPECT_T(atCharacterPtr[2] == 'u')) && (JK_EXPECT_T(atCharacterPtr[3] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeTrue, 4UL); } } + else if(JK_EXPECT_T(currentCharacter == 'f')) { if(!((JK_EXPECT_T((atCharacterPtr + 5UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'a')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 's')) && (JK_EXPECT_T(atCharacterPtr[4] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 5UL, JKTokenTypeFalse, 5UL); } } + else if(JK_EXPECT_T(currentCharacter == 'n')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'u')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 'l')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeNull, 4UL); } } + else { stopParsing = 1; /* XXX Add error message */ } + } + + if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); } + return(stopParsing); +} + +static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) { + NSString *acceptStrings[16]; + int acceptIdx = 0; + if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; } + if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; } + if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; } + if(acceptIdx == 1) { jk_error(parseState, @"Expected %@, not '%*.*s'", acceptStrings[0], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 2) { jk_error(parseState, @"Expected %@ or %@, not '%*.*s'", acceptStrings[0], acceptStrings[1], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } + else if(acceptIdx == 3) { jk_error(parseState, @"Expected %@, %@, or %@, not '%*.*s", acceptStrings[0], acceptStrings[1], acceptStrings[2], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } +} + +static void *jk_parse_array(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedArray = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [array] objectsIndex > %zu, resize failed? %@ line %#ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { + void *object = NULL; +#ifndef NS_BLOCK_ASSERTIONS + parseState->objectStack.objects[parseState->objectStack.index] = NULL; + parseState->objectStack.keys [parseState->objectStack.index] = NULL; +#endif + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL"); stopParsing = 1; break; } else { parseState->objectStack.objects[parseState->objectStack.index++] = object; arrayState = JKParseAcceptCommaOrEnd; } + break; + case JKTokenTypeArrayEnd: if(JK_EXPECT_T(arrayState & JKParseAcceptEnd)) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedArray = (void *)_JKArrayCreate((id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ']'."); } stopParsing = 1; break; + case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedArray == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedArray); +} + +static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) { + void *parsedDictionary = NULL; + + parseState->objectStack.index--; + + parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); + + return(parsedDictionary); +} + +static void *jk_parse_dictionary(JKParseState *parseState) { + size_t startingObjectIndex = parseState->objectStack.index; + int dictState = JKParseAcceptValueOrEnd, stopParsing = 0; + void *parsedDictionary = NULL; + + while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { + if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [dictionary] objectsIndex > %zu, resize failed? %@ line #%ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } + + size_t objectStackIndex = parseState->objectStack.index++; + parseState->objectStack.keys[objectStackIndex] = NULL; + parseState->objectStack.objects[objectStackIndex] = NULL; + void *key = NULL, *object = NULL; + + if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) { + switch(parseState->token.type) { + case JKTokenTypeString: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; } + if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; } + else { + parseState->objectStack.keys[objectStackIndex] = key; + if(JK_EXPECT_T(parseState->token.value.cacheItem != NULL)) { if(JK_EXPECT_F(parseState->token.value.cacheItem->cfHash == 0UL)) { parseState->token.value.cacheItem->cfHash = CFHash(key); } parseState->objectStack.cfHashes[objectStackIndex] = parseState->token.value.cacheItem->cfHash; } + else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); } + } + break; + + case JKTokenTypeObjectEnd: if((JK_EXPECT_T(dictState & JKParseAcceptEnd))) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedDictionary = jk_create_dictionary(parseState, startingObjectIndex); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected '}'."); } stopParsing = 1; break; + case JKTokenTypeComma: if((JK_EXPECT_T(dictState & JKParseAcceptComma))) { dictState = JKParseAcceptValue; parseState->objectStack.index--; continue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; + + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + + if(JK_EXPECT_T(stopParsing == 0)) { + if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { if(JK_EXPECT_F(parseState->token.type != JKTokenTypeSeparator)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Expected ':'."); stopParsing = 1; } } + } + + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeNumber: + case JKTokenTypeString: + case JKTokenTypeTrue: + case JKTokenTypeFalse: + case JKTokenTypeNull: + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: + if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } + if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL."); stopParsing = 1; break; } else { parseState->objectStack.objects[objectStackIndex] = object; dictState = JKParseAcceptCommaOrEnd; } + break; + default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break; + } + } + } + + if(JK_EXPECT_F(parsedDictionary == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.keys[idx] != NULL) { CFRelease(parseState->objectStack.keys[idx]); parseState->objectStack.keys[idx] = NULL; } if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } +#if !defined(NS_BLOCK_ASSERTIONS) + else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } +#endif + + parseState->objectStack.index = startingObjectIndex; + return(parsedDictionary); +} + +static id json_parse_it(JKParseState *parseState) { + id parsedObject = NULL; + int stopParsing = 0; + + while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) { + if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { + switch(parseState->token.type) { + case JKTokenTypeArrayBegin: + case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break; + default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break; + } + } + } + + NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); + + if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); } + if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); } + + if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_parse_skip_whitespace(parseState); + if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { + jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining."); + parsedObject = NULL; + } + } + + return(parsedObject); +} + +//////////// +#pragma mark - +#pragma mark Object cache + +// This uses a Galois Linear Feedback Shift Register (LFSR) PRNG to pick which item in the cache to age. It has a period of (2^32)-1. +// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. +JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { + NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U); + parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1; +} + +// The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts. +// +// The hash table is a linear C array of JKTokenCacheItem. The terms "item" and "bucket" are synonymous with the index in to the cache array, i.e. cache.items[bucket]. +// +// Items in the cache have an age associated with them. The age is the number of rightmost 1 bits, i.e. 0000 = 0, 0001 = 1, 0011 = 2, 0111 = 3, 1111 = 4. +// This allows us to use left and right shifts to add or subtract from an items age. Add = (age << 1) | 1. Subtract = age >> 0. Subtract is synonymous with "age" (i.e., age an item). +// The reason for this is it allows us to perform saturated adds and subtractions and is branchless. +// The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits. +// +// A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0. +// +// When an item is found in the cache, it's age is incremented. +// If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items. +// +// If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache. + +static void *jk_cachedObjects(JKParseState *parseState) { + unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL; + void *parsedAtom = NULL; + + if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); } + + for(x = 0UL; x < JK_CACHE_PROBES; x++) { + if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; } + + if((JK_EXPECT_T(parseState->cache.items[bucket].hash == parseState->token.value.hash)) && (JK_EXPECT_T(parseState->cache.items[bucket].size == parseState->token.value.ptrRange.length)) && (JK_EXPECT_T(parseState->cache.items[bucket].type == parseState->token.value.type)) && (JK_EXPECT_T(parseState->cache.items[bucket].bytes != NULL)) && (JK_EXPECT_T(strncmp((const char *)parseState->cache.items[bucket].bytes, (const char *)parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) { + parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U; + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + NSCParameterAssert(parseState->cache.items[bucket].object != NULL); + return((void *)CFRetain(parseState->cache.items[bucket].object)); + } else { + if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; } + if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); } + // This is the open addressing function. The values length and type are used as a form of "double hashing" to distribute values with the same effective value hash across different object cache buckets. + // The values type is a prime number that is relatively coprime to the other primes in the set of value types and the number of hash table buckets. + bucket = (parseState->token.value.hash + (parseState->token.value.ptrRange.length * (x + 1UL)) + (parseState->token.value.type * (x + 1UL)) + (3UL * (x + 1UL))) & (parseState->cache.count - 1UL); + } + } + + switch(parseState->token.value.type) { + case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break; + case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break; + case JKValueTypeUnsignedLongLong: + if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); } + else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); } + break; + case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break; + default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) { + bucket = useableBucket; + if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; } + + if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) { + memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length); + parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom); + parseState->cache.items[bucket].hash = parseState->token.value.hash; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length; + parseState->cache.items[bucket].type = parseState->token.value.type; + parseState->token.value.cacheItem = &parseState->cache.items[bucket]; + parseState->cache.age[bucket] = JK_INIT_CACHE_AGE; + } else { // The realloc failed, so clear the appropriate fields. + parseState->cache.items[bucket].hash = 0UL; + parseState->cache.items[bucket].cfHash = 0UL; + parseState->cache.items[bucket].size = 0UL; + parseState->cache.items[bucket].type = 0UL; + } + } + + return(parsedAtom); +} + + +static void *jk_object_for_token(JKParseState *parseState) { + void *parsedAtom = NULL; + + parseState->token.value.cacheItem = NULL; + switch(parseState->token.type) { + case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break; + case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break; + case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break; + case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break; + case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break; + case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break; + default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; + } + + return(parsedAtom); +} + +#pragma mark - +@implementation JSONDecoder + +static Class _jk_NSNumberClass; +static NSNumberAllocImp _jk_NSNumberAllocImp; +static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp; + ++ (void)load +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal. + + _jk_NSNumberClass = [NSNumber class]; + _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)]; + + // Hacktacular. Need to do it this way due to the nature of class clusters. + id temp_NSNumber = [NSNumber alloc]; + _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)]; + [[temp_NSNumber init] release]; + temp_NSNumber = NULL; + + [pool release]; pool = NULL; +} + ++ (id)decoder +{ + return([self decoderWithParseOptions:JKParseOptionStrict]); +} + ++ (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]); +} + +- (id)init +{ + return([self initWithParseOptions:JKParseOptionStrict]); +} + +- (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + if((self = [super init]) == NULL) { return(NULL); } + + if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; } + + if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; } + + parseState->parseOptionFlags = parseOptionFlags; + + parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL; + parseState->objectStack.roundSizeUpToMultipleOf = 2048UL; + + parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass; + parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp; + parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp; + + parseState->cache.prng_lfsr = 1U; + parseState->cache.count = JK_CACHE_SLOTS; + if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; } + + return(self); + +errorExit: + if(self) { [self autorelease]; self = NULL; } + return(NULL); +} + +// This is here primarily to support the NSString and NSData convenience functions so the autoreleased JSONDecoder can release most of its resources before the pool pops. +static void _JSONDecoderCleanup(JSONDecoder *decoder) { + if((decoder != NULL) && (decoder->parseState != NULL)) { + jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer); + jk_objectStack_release(&decoder->parseState->objectStack); + + [decoder clearCache]; + if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; } + + free(decoder->parseState); decoder->parseState = NULL; + } +} + +- (void)dealloc +{ + _JSONDecoderCleanup(self); + [super dealloc]; +} + +- (void)clearCache +{ + if(JK_EXPECT_T(parseState != NULL)) { + if(JK_EXPECT_T(parseState->cache.items != NULL)) { + size_t idx = 0UL; + for(idx = 0UL; idx < parseState->cache.count; idx++) { + if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; } + if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; } + memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem)); + parseState->cache.age[idx] = 0U; + } + } + } +} + +// This needs to be completely rewritten. +static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) { + NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U)); + parseState->stringBuffer.bytes.ptr = string; + parseState->stringBuffer.bytes.length = length; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = (mutableCollections == NO) ? NO : YES; + + unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer)); + + void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64); + void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64); + CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64); + jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS); + + id parsedJSON = json_parse_it(parseState); + + if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; } + + jk_managedBuffer_release(&parseState->token.tokenBuffer); + jk_objectStack_release(&parseState->objectStack); + + parseState->stringBuffer.bytes.ptr = NULL; + parseState->stringBuffer.bytes.length = 0UL; + parseState->atIndex = 0UL; + parseState->lineNumber = 1UL; + parseState->lineStartIndex = 0UL; + parseState->prev_atIndex = 0UL; + parseState->prev_lineNumber = 1UL; + parseState->prev_lineStartIndex = 0UL; + parseState->error = NULL; + parseState->errorIsPrev = 0; + parseState->mutableCollections = NO; + + return(parsedJSON); +} + +//////////// +#pragma mark Deprecated as of v1.4 +//////////// + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. +- (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error +{ + return([self objectWithUTF8String:string length:length error:error]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData: instead. +- (id)parseJSONData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +// Deprecated in JSONKit v1.4. Use objectWithData:error: instead. +- (id)parseJSONData:(NSData *)jsonData error:(NSError **)error +{ + return([self objectWithData:jsonData error:error]); +} + +//////////// +#pragma mark Methods that return immutable collection objects +//////////// + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self objectWithUTF8String:string length:length error:NULL]); +} + +- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error)); +} + +- (id)objectWithData:(NSData *)jsonData +{ + return([self objectWithData:jsonData error:NULL]); +} + +- (id)objectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +//////////// +#pragma mark Methods that return mutable collection objects +//////////// + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length +{ + return([self mutableObjectWithUTF8String:string length:length error:NULL]); +} + +- (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error +{ + if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } + if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } + + return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error)); +} + +- (id)mutableObjectWithData:(NSData *)jsonData +{ + return([self mutableObjectWithData:jsonData error:NULL]); +} + +- (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error +{ + if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } + return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); +} + +@end + +/* + The NSString and NSData convenience methods need a little bit of explanation. + + Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like + + const unsigned char *utf8String = (const unsigned char *)[self UTF8String]; + if(utf8String == NULL) { return(NULL); } + size_t utf8Length = strlen((const char *)utf8String); + return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]); + + This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is + allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed. + + In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead. + + Now we use an autoreleased CFMutableData that is sized to the UTF8 length of the NSString in question and is used to hold the UTF8 + conversion of said string. + + Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free + the buffer. + + Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved + to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls + _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used + again. + + If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the + autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in + autorelease limbo. It's more complicated for us, but a win for the user. + + Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our + requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in + autorelease limbo, but we've done our best to minimize that impact, so it all balances out. + */ + +@implementation NSString (JSONKitDeserializing) + +static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) { + id returnObject = NULL; + CFMutableDataRef mutableData = NULL; + JSONDecoder *decoder = NULL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString); + NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) { + UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData); + CFIndex usedBytes = 0L, convertedCount = 0L; + + convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { if(error != NULL) { *error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:[NSDictionary dictionaryWithObject:@"An error occurred converting the contents of a NSString to UTF8." forKey:NSLocalizedDescriptionKey]]; } goto exitNow; } + + if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } + } + +exitNow: + if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); } + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)objectFromJSONString +{ + return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO)); +} + + +- (id)mutableObjectFromJSONString +{ + return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES)); +} + +@end + +@implementation NSData (JSONKitDeserializing) + +- (id)objectFromJSONData +{ + return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + +- (id)mutableObjectFromJSONData +{ + return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags +{ + return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); +} + +- (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error +{ + JSONDecoder *decoder = NULL; + id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error]; + if(decoder != NULL) { _JSONDecoderCleanup(decoder); } + return(returnObject); +} + + +@end + +//////////// +#pragma mark - +#pragma mark Encoding / deserializing functions + +static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) { + NSCParameterAssert((encodeState != NULL) && (format != NULL)); + + va_list varArgsList; + va_start(varArgsList, format); + NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; + va_end(varArgsList); + + if(encodeState->error == NULL) { + encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: + [NSDictionary dictionaryWithObjectsAndKeys: + formatString, NSLocalizedDescriptionKey, + NULL]]; + } +} + +JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) { + NSCParameterAssert(encodeState != NULL); + if(JK_EXPECT_T(cacheSlot != NULL)) { + NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex)); + cacheSlot->object = object; + cacheSlot->offset = startingAtIndex; + cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex); + } +} + +static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) { + va_list varArgsList, varArgsListCopy; + va_start(varArgsList, format); + va_copy(varArgsListCopy, varArgsList); + + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + + ssize_t formattedStringLength = 0L; + int returnValue = 0; + + if(JK_EXPECT_T((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsList)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { + NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)); + if(JK_EXPECT_F(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (formattedStringLength * 2UL)+ 4096UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); returnValue = 1; goto exitNow; } + if(JK_EXPECT_F((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsListCopy)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { jk_encode_error(encodeState, @"vsnprintf failed unexpectedly."); returnValue = 1; goto exitNow; } + } + +exitNow: + va_end(varArgsList); + va_end(varArgsListCopy); + if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); } + return(returnValue); +} + +static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); + if(JK_EXPECT_F(((encodeState->atIndex + strlen(format) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + strlen(format) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + size_t formatIdx = 0UL; + for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) { + NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_T(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n'; + size_t depthWhiteSpace = 0UL; + for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + return(0); +} + +static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (format != NULL) && ((depthChange >= -1L) && (depthChange <= 1L)) && ((encodeState->depth == 0UL) ? (depthChange >= 0L) : 1) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); + if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + encodeState->depth += depthChange; + if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } + else { + if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; + if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } + } + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + return(0); +} + +static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL)); + if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; } + else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); } + return(0); +} + +static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex)); + if(JK_EXPECT_F((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < (length + 4UL))) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL + length) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } } + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length); + encodeState->atIndex += length; + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); + return(0); +} + +JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) { + return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) ); +} + +static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) { + NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL)); + + id object = (id)objectPtr, encodeCacheObject = object; + int isClass = JKClassUnknown; + size_t startingAtIndex = encodeState->atIndex; + + JKHash objectHash = jk_encode_object_hash(objectPtr); + JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS]; + + if(JK_EXPECT_T(cacheSlot->object == object)) { + NSCParameterAssert((cacheSlot->object != NULL) && + (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) && + (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length))); + if(JK_EXPECT_F(((encodeState->atIndex + cacheSlot->length + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + cacheSlot->length + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && + ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex))); + memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length); + encodeState->atIndex += cacheSlot->length; + return(0); + } + + // When we encounter a class that we do not handle, and we have either a delegate or block that the user supplied to format unsupported classes, + // we "re-run" the object check. However, we re-run the object check exactly ONCE. If the user supplies an object that isn't one of the + // supported classes, we fail the second type (i.e., double fault error). + BOOL rerunningAfterClassFormatter = NO; +rerunAfterClassFormatter: + if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } + else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } + else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } + else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } + else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } + else { + if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { encodeState->fastClassLookup.stringClass = object->isa; isClass = JKClassString; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { encodeState->fastClassLookup.numberClass = object->isa; isClass = JKClassNumber; } + else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { encodeState->fastClassLookup.dictionaryClass = object->isa; isClass = JKClassDictionary; } + else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { encodeState->fastClassLookup.arrayClass = object->isa; isClass = JKClassArray; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { encodeState->fastClassLookup.nullClass = object->isa; isClass = JKClassNull; } + else { + if((rerunningAfterClassFormatter == NO) && ( +#ifdef __BLOCKS__ + ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) || +#endif + ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; } + + if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); } + else { jk_encode_error(encodeState, @"Unable to serialize object class %@ that was returned by the unsupported class formatter. Original object class was %@.", (object == NULL) ? @"NULL" : NSStringFromClass([object class]), NSStringFromClass([encodeCacheObject class])); return(1); } + } + } + + // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray + // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro: + // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) + int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1; + + switch(isClass) { + case JKClassString: + { + { + const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman); + if(cStringPtr != NULL) { + const unsigned char *utf8String = cStringPtr; + size_t utf8Idx = 0UL; + + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + if(JK_EXPECT_F(((encodeState->atIndex + (stringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (stringLength * 2UL) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; } + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + + slowUTF8Path: + { + CFIndex stringLength = CFStringGetLength((CFStringRef)object); + CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L; + + if(JK_EXPECT_F((size_t)maxStringUTF8Length > encodeState->utf8ConversionBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->utf8ConversionBuffer, maxStringUTF8Length + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + CFIndex usedBytes = 0L, convertedCount = 0L; + convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes); + if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { jk_encode_error(encodeState, @"An error occurred converting the contents of a NSString to UTF8."); return(1); } + + if(JK_EXPECT_F((encodeState->atIndex + (maxStringUTF8Length * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (maxStringUTF8Length * 2UL) + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } + + const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr; + + size_t utf8Idx = 0UL; + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) { + NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); + NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); + NSCParameterAssert((CFIndex)utf8Idx < usedBytes); + if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { + switch(utf8String[utf8Idx]) { + case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; + case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; + case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; + case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; + case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; + default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) { + const unsigned char *nextValidCharacter = NULL; + UTF32 u32ch = 0U; + ConversionResult result; + + if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); } + else { + utf8Idx = (nextValidCharacter - utf8String) - 1UL; + if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } } + else { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x\\u%4.4x", (0xd7c0U + (u32ch >> 10)), (0xdc00U + (u32ch & 0x3ffU))))) { return(1); } } + } + } else { + if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } + encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; + } + } + } + NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); + if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } + jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); + return(0); + } + } + break; + + case JKClassNumber: + { + if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); } + else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); } + + const char *objCType = [object objCType]; + char anum[256], *aptr = &anum[255]; + int isNegative = 0; + unsigned long long ullv; + long long llv; + + if(JK_EXPECT_F(objCType == NULL) || JK_EXPECT_F(objCType[0] == 0) || JK_EXPECT_F(objCType[1] != 0)) { jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%s'", (objCType == NULL) ? "" : objCType); return(1); } + + switch(objCType[0]) { + case 'c': case 'i': case 's': case 'l': case 'q': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) { + if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; } + goto convertNumber; + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B': + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) { + convertNumber: + if(JK_EXPECT_F(ullv < 10ULL)) { *--aptr = ullv + '0'; } else { while(JK_EXPECT_T(ullv > 0ULL)) { *--aptr = (ullv % 10ULL) + '0'; ullv /= 10ULL; NSCParameterAssert(aptr > anum); } } + if(isNegative) { *--aptr = '-'; } + NSCParameterAssert(aptr > anum); + return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr)); + } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } + break; + case 'f': case 'd': + { + double dv; + if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) { + if(JK_EXPECT_F(!isfinite(dv))) { jk_encode_error(encodeState, @"Floating point values must be finite. JSON does not support NaN or Infinity."); return(1); } + return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv)); + } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); } + } + break; + default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break; + } + } + break; + + case JKClassArray: + { + int printComma = 0; + CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L; + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); } + if(JK_EXPECT_F(arrayCount > 1020L)) { + for(id arrayObject in object) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, arrayObject))) { return(1); } } + } else { + void *objects[1024]; + CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects); + for(idx = 0L; idx < arrayCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } } + } + return(jk_encode_write1(encodeState, -1L, "]")); + } + break; + + case JKClassDictionary: + { + int printComma = 0; + CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L; + id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object; + + if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); } + if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) { + for(id keyObject in enumerateObject) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + if(JK_EXPECT_F((keyObject->isa != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); } + } + } else { + void *keys[1024], *objects[1024]; + CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects); + for(idx = 0L; idx < dictionaryCount; idx++) { + if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } + printComma = 1; + if(JK_EXPECT_F(((id)keys[idx])->isa != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); } + if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } + if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } + } + } + return(jk_encode_write1(encodeState, -1L, "}")); + } + break; + + case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break; + + default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break; + } + + return(0); +} + + +@implementation JKSerializer + ++ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]); +} + +- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ +#ifndef __BLOCKS__ +#pragma unused(block) +#endif + NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) && + (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) && + (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1)); + + id returnObject = NULL; + + if(encodeState != NULL) { [self releaseState]; } + if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); } + + if((error != NULL) && (*error != NULL)) { *error = NULL; } + + if(delegate != NULL) { + if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; } + if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; } + encodeState->classFormatterDelegate = delegate; + encodeState->classFormatterSelector = selector; + encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector]; + NSCParameterAssert(encodeState->classFormatterIMP != NULL); + } + +#ifdef __BLOCKS__ + encodeState->classFormatterBlock = block; +#endif + encodeState->serializeOptionFlags = optionFlags; + encodeState->encodeOption = encodeOption; + encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL); + encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL; + + unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer)); + + unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64); + jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer)); + + if(((encodeOption & JKEncodeOptionCollectionObj) != 0UL) && (([object isKindOfClass:[NSArray class]] == NO) && ([object isKindOfClass:[NSDictionary class]] == NO))) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSArray or NSDictionary.", NSStringFromClass([object class])); goto errorExit; } + if(((encodeOption & JKEncodeOptionStringObj) != 0UL) && ([object isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSString.", NSStringFromClass([object class])); goto errorExit; } + + if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) { + BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO; + + if((encodeState->atIndex < 2UL)) + if((stackBuffer == NO) && ((encodeState->stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState->stringBuffer.bytes.ptr, encodeState->atIndex + 16UL)) == NULL)) { jk_encode_error(encodeState, @"Unable to realloc buffer"); goto errorExit; } + + switch((encodeOption & JKEncodeOptionAsTypeMask)) { + case JKEncodeOptionAsData: + if(stackBuffer == YES) { if((returnObject = [(id)CFDataCreate( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + else { if((returnObject = [(id)CFDataCreateWithBytesNoCopy( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } + break; + + case JKEncodeOptionAsString: + if(stackBuffer == YES) { if((returnObject = [(id)CFStringCreateWithBytes( NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + else { if((returnObject = [(id)CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } + break; + + default: jk_encode_error(encodeState, @"Unknown encode as type."); break; + } + + if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; } + } + +errorExit: + if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; } + [self releaseState]; + + return(returnObject); +} + +- (void)releaseState +{ + if(encodeState != NULL) { + jk_managedBuffer_release(&encodeState->stringBuffer); + jk_managedBuffer_release(&encodeState->utf8ConversionBuffer); + free(encodeState); encodeState = NULL; + } +} + +- (void)dealloc +{ + [self releaseState]; + [super dealloc]; +} + +@end + +@implementation NSString (JSONKitSerializing) + +//////////// +#pragma mark Methods for serializing a single NSString. +//////////// + +// Useful for those who need to serialize just a NSString. Otherwise you would have to do something like [NSArray arrayWithObject:stringToBeJSONSerialized], serializing the array, and then chopping of the extra ^\[.*\]$ square brackets. + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSArray (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializing) + +// NSData returning methods... + +- (NSData *)JSONData +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +// NSString returning methods... + +- (NSString *)JSONString +{ + return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); +} + +@end + + +#ifdef __BLOCKS__ + +@implementation NSArray (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +@implementation NSDictionary (JSONKitSerializingBlockAdditions) + +- (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +- (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error +{ + return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); +} + +@end + +#endif // __BLOCKS__ diff --git a/iOS Example/Vendor/TTT/TTTLocationFormatter.h b/iOS Example/Vendor/TTT/TTTLocationFormatter.h new file mode 100644 index 0000000..be7a374 --- /dev/null +++ b/iOS Example/Vendor/TTT/TTTLocationFormatter.h @@ -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 +#import + +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 diff --git a/iOS Example/Vendor/TTT/TTTLocationFormatter.m b/iOS Example/Vendor/TTT/TTTLocationFormatter.m new file mode 100644 index 0000000..ff40065 --- /dev/null +++ b/iOS Example/Vendor/TTT/TTTLocationFormatter.m @@ -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 diff --git a/Example/main.m b/iOS Example/main.m similarity index 100% rename from Example/main.m rename to iOS Example/main.m From d7b6046e63c14a6e9c1ed5f91855bea20177f924 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Fri, 23 Sep 2011 12:30:50 -0500 Subject: [PATCH 03/65] Adding AFNetworking.h Renaming App Delegate --- AFNetworking/AFNetworking.h | 35 + AFNetworking/UIImageView+AFNetworking.h | 2 +- .../project.pbxproj | 14 +- ...Mac_ExampleAppDelegate.h => AppDelegate.h} | 2 +- ...Mac_ExampleAppDelegate.m => AppDelegate.m} | 4 +- .../en.lproj/MainMenu.xib | 2294 +---------------- 6 files changed, 141 insertions(+), 2210 deletions(-) create mode 100644 AFNetworking/AFNetworking.h rename Mac Example/AFNetworking Mac Example/{AFNetworking_Mac_ExampleAppDelegate.h => AppDelegate.h} (76%) rename Mac Example/AFNetworking Mac Example/{AFNetworking_Mac_ExampleAppDelegate.m => AppDelegate.m} (77%) diff --git a/AFNetworking/AFNetworking.h b/AFNetworking/AFNetworking.h new file mode 100644 index 0000000..0f010a6 --- /dev/null +++ b/AFNetworking/AFNetworking.h @@ -0,0 +1,35 @@ +// 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 +#import + +#import +#import +#import + +#import +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#endif diff --git a/AFNetworking/UIImageView+AFNetworking.h b/AFNetworking/UIImageView+AFNetworking.h index 03e14f5..a7aef6c 100644 --- a/AFNetworking/UIImageView+AFNetworking.h +++ b/AFNetworking/UIImageView+AFNetworking.h @@ -68,7 +68,7 @@ */ - (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; diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index b1fc532..322df20 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -18,7 +18,7 @@ F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */; }; F8CEEB7B142CEC6E00247B03 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB7A142CEC6E00247B03 /* main.m */; }; F8CEEB7F142CEC6E00247B03 /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB7D142CEC6E00247B03 /* Credits.rtf */; }; - F8CEEB82142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */; }; + F8CEEB82142CEC6E00247B03 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB81142CEC6E00247B03 /* AppDelegate.m */; }; F8CEEB85142CEC6E00247B03 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB83142CEC6E00247B03 /* MainMenu.xib */; }; /* End PBXBuildFile section */ @@ -39,6 +39,7 @@ F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; F8A27A38142CF36100F5E0D6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; F8A27A39142CF36100F5E0D6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; + F8A27A3B142CF75A00F5E0D6 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = AFNetworking/AFNetworking.h; sourceTree = ""; }; 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; }; @@ -48,8 +49,8 @@ F8CEEB7A142CEC6E00247B03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; F8CEEB7C142CEC6E00247B03 /* Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; F8CEEB7E142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = en; path = en.lproj/Credits.rtf; sourceTree = ""; }; - F8CEEB80142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AFNetworking_Mac_ExampleAppDelegate.h; sourceTree = ""; }; - F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AFNetworking_Mac_ExampleAppDelegate.m; sourceTree = ""; }; + F8CEEB80142CEC6E00247B03 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + F8CEEB81142CEC6E00247B03 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; F8CEEB84142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/MainMenu.xib; sourceTree = ""; }; /* End PBXFileReference section */ @@ -115,8 +116,8 @@ F8CEEB74142CEC6E00247B03 /* AFNetworking Mac Example */ = { isa = PBXGroup; children = ( - F8CEEB80142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.h */, - F8CEEB81142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m */, + F8CEEB80142CEC6E00247B03 /* AppDelegate.h */, + F8CEEB81142CEC6E00247B03 /* AppDelegate.m */, F8CEEB83142CEC6E00247B03 /* MainMenu.xib */, F8CEEB75142CEC6E00247B03 /* Supporting Files */, ); @@ -146,6 +147,7 @@ F8CEEB8C142CED6F00247B03 /* AFNetworking */ = { isa = PBXGroup; children = ( + F8A27A3B142CF75A00F5E0D6 /* AFNetworking.h */, F8A27A20142CF24700F5E0D6 /* AFHTTPRequestOperation.h */, F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */, F8A27A26142CF24700F5E0D6 /* AFJSONRequestOperation.h */, @@ -229,7 +231,7 @@ buildActionMask = 2147483647; files = ( F8CEEB7B142CEC6E00247B03 /* main.m in Sources */, - F8CEEB82142CEC6E00247B03 /* AFNetworking_Mac_ExampleAppDelegate.m in Sources */, + F8CEEB82142CEC6E00247B03 /* AppDelegate.m in Sources */, F8A27A2C142CF24700F5E0D6 /* AFHTTPClient.m in Sources */, F8A27A2D142CF24700F5E0D6 /* AFHTTPRequestOperation.m in Sources */, F8A27A2E142CF24700F5E0D6 /* AFImageCache.m in Sources */, diff --git a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h b/Mac Example/AFNetworking Mac Example/AppDelegate.h similarity index 76% rename from Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h rename to Mac Example/AFNetworking Mac Example/AppDelegate.h index 6981127..2c777c5 100644 --- a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.h +++ b/Mac Example/AFNetworking Mac Example/AppDelegate.h @@ -8,7 +8,7 @@ #import -@interface AFNetworking_Mac_ExampleAppDelegate : NSObject { +@interface AppDelegate : NSObject { NSWindow *_window; } diff --git a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m b/Mac Example/AFNetworking Mac Example/AppDelegate.m similarity index 77% rename from Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m rename to Mac Example/AFNetworking Mac Example/AppDelegate.m index fc334b8..99ed16e 100644 --- a/Mac Example/AFNetworking Mac Example/AFNetworking_Mac_ExampleAppDelegate.m +++ b/Mac Example/AFNetworking Mac Example/AppDelegate.m @@ -6,9 +6,9 @@ // Copyright 2011年 Gowalla. All rights reserved. // -#import "AFNetworking_Mac_ExampleAppDelegate.h" +#import "AppDelegate.h" -@implementation AFNetworking_Mac_ExampleAppDelegate +@implementation AppDelegate @synthesize window = _window; diff --git a/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib b/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib index 17c2105..ed5f98c 100644 --- a/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib +++ b/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib @@ -1,20 +1,20 @@ - 1070 - 10J869 - 1839 - 1038.35 - 461.00 + 0 + 11A511 + 1900 + 1138 + 566.00 com.apple.InterfaceBuilder.CocoaPlugin - 1839 + 1900 YES - NSMenu NSWindowTemplate NSView + NSMenu NSMenuItem NSCustomObject @@ -1322,16 +1322,21 @@ AFNetworking Mac Example NSWindow + - + 256 {480, 360} + + + {{0, 0}, {1920, 1178}} - {1e+13, 1e+13} + {10000000000000, 10000000000000} + YES - AFNetworking_Mac_ExampleAppDelegate + AppDelegate NSFontManager @@ -3073,144 +3078,69 @@ -2.IBPluginDependency -3.IBPluginDependency 112.IBPluginDependency - 112.ImportedFromIB2 124.IBPluginDependency - 124.ImportedFromIB2 125.IBPluginDependency - 125.ImportedFromIB2 - 125.editorWindowContentRectSynchronizationRect 126.IBPluginDependency - 126.ImportedFromIB2 129.IBPluginDependency - 129.ImportedFromIB2 130.IBPluginDependency - 130.ImportedFromIB2 - 130.editorWindowContentRectSynchronizationRect 131.IBPluginDependency - 131.ImportedFromIB2 134.IBPluginDependency - 134.ImportedFromIB2 136.IBPluginDependency - 136.ImportedFromIB2 143.IBPluginDependency - 143.ImportedFromIB2 144.IBPluginDependency - 144.ImportedFromIB2 145.IBPluginDependency - 145.ImportedFromIB2 149.IBPluginDependency - 149.ImportedFromIB2 150.IBPluginDependency - 150.ImportedFromIB2 19.IBPluginDependency - 19.ImportedFromIB2 195.IBPluginDependency - 195.ImportedFromIB2 196.IBPluginDependency - 196.ImportedFromIB2 197.IBPluginDependency - 197.ImportedFromIB2 198.IBPluginDependency - 198.ImportedFromIB2 199.IBPluginDependency - 199.ImportedFromIB2 - 200.IBEditorWindowLastContentRect 200.IBPluginDependency - 200.ImportedFromIB2 - 200.editorWindowContentRectSynchronizationRect 201.IBPluginDependency - 201.ImportedFromIB2 202.IBPluginDependency - 202.ImportedFromIB2 203.IBPluginDependency - 203.ImportedFromIB2 204.IBPluginDependency - 204.ImportedFromIB2 - 205.IBEditorWindowLastContentRect 205.IBPluginDependency - 205.ImportedFromIB2 - 205.editorWindowContentRectSynchronizationRect 206.IBPluginDependency - 206.ImportedFromIB2 207.IBPluginDependency - 207.ImportedFromIB2 208.IBPluginDependency - 208.ImportedFromIB2 209.IBPluginDependency - 209.ImportedFromIB2 210.IBPluginDependency - 210.ImportedFromIB2 211.IBPluginDependency - 211.ImportedFromIB2 212.IBPluginDependency - 212.ImportedFromIB2 - 212.editorWindowContentRectSynchronizationRect 213.IBPluginDependency - 213.ImportedFromIB2 214.IBPluginDependency - 214.ImportedFromIB2 215.IBPluginDependency - 215.ImportedFromIB2 216.IBPluginDependency - 216.ImportedFromIB2 217.IBPluginDependency - 217.ImportedFromIB2 218.IBPluginDependency - 218.ImportedFromIB2 219.IBPluginDependency - 219.ImportedFromIB2 - 220.IBEditorWindowLastContentRect 220.IBPluginDependency - 220.ImportedFromIB2 - 220.editorWindowContentRectSynchronizationRect 221.IBPluginDependency - 221.ImportedFromIB2 23.IBPluginDependency - 23.ImportedFromIB2 236.IBPluginDependency - 236.ImportedFromIB2 239.IBPluginDependency - 239.ImportedFromIB2 - 24.IBEditorWindowLastContentRect 24.IBPluginDependency - 24.ImportedFromIB2 - 24.editorWindowContentRectSynchronizationRect - 29.IBEditorWindowLastContentRect 29.IBPluginDependency - 29.ImportedFromIB2 - 29.WindowOrigin - 29.editorWindowContentRectSynchronizationRect 295.IBPluginDependency - 296.IBEditorWindowLastContentRect 296.IBPluginDependency - 296.editorWindowContentRectSynchronizationRect 297.IBPluginDependency 298.IBPluginDependency 346.IBPluginDependency - 346.ImportedFromIB2 348.IBPluginDependency - 348.ImportedFromIB2 - 349.IBEditorWindowLastContentRect 349.IBPluginDependency - 349.ImportedFromIB2 - 349.editorWindowContentRectSynchronizationRect 350.IBPluginDependency - 350.ImportedFromIB2 351.IBPluginDependency - 351.ImportedFromIB2 354.IBPluginDependency - 354.ImportedFromIB2 - 371.IBEditorWindowLastContentRect 371.IBPluginDependency 371.IBWindowTemplateEditedContentRect 371.NSWindowTemplate.visibleAtLaunch - 371.editorWindowContentRectSynchronizationRect 372.IBPluginDependency 375.IBPluginDependency - 376.IBEditorWindowLastContentRect 376.IBPluginDependency 377.IBPluginDependency - 388.IBEditorWindowLastContentRect 388.IBPluginDependency 389.IBPluginDependency 390.IBPluginDependency @@ -3245,7 +3175,6 @@ 419.IBPluginDependency 420.IBPluginDependency 450.IBPluginDependency - 451.IBEditorWindowLastContentRect 451.IBPluginDependency 452.IBPluginDependency 453.IBPluginDependency @@ -3258,17 +3187,14 @@ 466.IBPluginDependency 485.IBPluginDependency 490.IBPluginDependency - 491.IBEditorWindowLastContentRect 491.IBPluginDependency 492.IBPluginDependency 494.IBPluginDependency 496.IBPluginDependency - 497.IBEditorWindowLastContentRect 497.IBPluginDependency 498.IBPluginDependency 499.IBPluginDependency 5.IBPluginDependency - 5.ImportedFromIB2 500.IBPluginDependency 501.IBPluginDependency 502.IBPluginDependency @@ -3277,7 +3203,6 @@ 505.IBPluginDependency 506.IBPluginDependency 507.IBPluginDependency - 508.IBEditorWindowLastContentRect 508.IBPluginDependency 509.IBPluginDependency 510.IBPluginDependency @@ -3289,39 +3214,20 @@ 516.IBPluginDependency 517.IBPluginDependency 534.IBPluginDependency - 534.ImportedFromIB2 56.IBPluginDependency - 56.ImportedFromIB2 - 57.IBEditorWindowLastContentRect 57.IBPluginDependency - 57.ImportedFromIB2 - 57.editorWindowContentRectSynchronizationRect 58.IBPluginDependency - 58.ImportedFromIB2 72.IBPluginDependency - 72.ImportedFromIB2 73.IBPluginDependency - 73.ImportedFromIB2 74.IBPluginDependency - 74.ImportedFromIB2 75.IBPluginDependency - 75.ImportedFromIB2 77.IBPluginDependency - 77.ImportedFromIB2 78.IBPluginDependency - 78.ImportedFromIB2 79.IBPluginDependency - 79.ImportedFromIB2 - 81.IBEditorWindowLastContentRect 81.IBPluginDependency - 81.ImportedFromIB2 - 81.editorWindowContentRectSynchronizationRect 82.IBPluginDependency - 82.ImportedFromIB2 83.IBPluginDependency - 83.ImportedFromIB2 92.IBPluginDependency - 92.ImportedFromIB2 YES @@ -3329,144 +3235,69 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{522, 812}, {146, 23}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{436, 809}, {64, 6}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{753, 187}, {275, 113}} - com.apple.InterfaceBuilder.CocoaPlugin - - {{608, 612}, {275, 83}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{547, 180}, {254, 283}} - com.apple.InterfaceBuilder.CocoaPlugin - - {{187, 434}, {243, 243}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{608, 612}, {167, 43}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{753, 217}, {238, 103}} - com.apple.InterfaceBuilder.CocoaPlugin - - {{608, 612}, {241, 103}} - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - com.apple.InterfaceBuilder.CocoaPlugin - - {{654, 239}, {194, 73}} - com.apple.InterfaceBuilder.CocoaPlugin - - {{525, 802}, {197, 73}} - {{380, 836}, {512, 20}} - com.apple.InterfaceBuilder.CocoaPlugin - - {74, 862} - {{6, 978}, {478, 20}} - com.apple.InterfaceBuilder.CocoaPlugin - {{604, 269}, {231, 43}} - com.apple.InterfaceBuilder.CocoaPlugin - {{475, 832}, {234, 43}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - {{746, 287}, {220, 133}} com.apple.InterfaceBuilder.CocoaPlugin - - {{608, 612}, {215, 63}} com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - {{380, 496}, {480, 360}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin {{380, 496}, {480, 360}} - {{33, 99}, {480, 360}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{591, 420}, {83, 43}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{523, 2}, {178, 283}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin @@ -3501,7 +3332,6 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{753, 197}, {170, 63}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin @@ -3514,17 +3344,14 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{725, 289}, {246, 23}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{674, 260}, {204, 183}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin @@ -3533,7 +3360,6 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - {{878, 180}, {164, 173}} com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin @@ -3545,39 +3371,20 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - {{286, 129}, {275, 183}} com.apple.InterfaceBuilder.CocoaPlugin - - {{23, 794}, {245, 183}} com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - - {{452, 109}, {196, 203}} com.apple.InterfaceBuilder.CocoaPlugin - - {{145, 474}, {199, 203}} com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - @@ -3598,1193 +3405,42 @@ YES - ABCardController + AppDelegate NSObject - - YES - - YES - addCardViewField: - copy: - cut: - doDelete: - find: - paste: - saveChanges: - - - YES - id - id - id - id - id - id - id - - - - YES - - YES - addCardViewField: - copy: - cut: - doDelete: - find: - paste: - saveChanges: - - - YES - - addCardViewField: - id - - - copy: - id - - - cut: - id - - - doDelete: - id - - - find: - id - - - paste: - id - - - saveChanges: - id - - - - YES - - YES - mCardView - mEditButton - mManagedObjectContext - mSearchField - mStatusTextField - mWindow - - - YES - ABCardView - NSButton - NSManagedObjectContext - NSSearchField - NSTextField - NSWindow - + window + NSWindow - YES - - YES - mCardView - mEditButton - mManagedObjectContext - mSearchField - mStatusTextField - mWindow - - - YES - - mCardView - ABCardView - - - mEditButton - NSButton - - - mManagedObjectContext - NSManagedObjectContext - - - mSearchField - NSSearchField - - - mStatusTextField - NSTextField - - - mWindow - NSWindow - - - - - IBProjectSource - ./Classes/ABCardController.h - - - - ABCardView - NSView - - YES - - YES - commitAndSave: - statusImageClicked: - - - YES - id - id - - - - YES - - YES - commitAndSave: - statusImageClicked: - - - YES - - commitAndSave: - id - - - statusImageClicked: - id - - - - - YES - - YES - mBuddyStatusImage - mHeaderView - mNameView - mNextKeyView - mUserImage - mUserImageView - - - YES - NSImageView - NSView - ABNameFrameView - NSView - NSImage - ABImageView - - - - YES - - YES - mBuddyStatusImage - mHeaderView - mNameView - mNextKeyView - mUserImage - mUserImageView - - - YES - - mBuddyStatusImage - NSImageView - - - mHeaderView - NSView - - - mNameView - ABNameFrameView - - - mNextKeyView - NSView - - - mUserImage - NSImage - - - mUserImageView - ABImageView - - - - - IBProjectSource - ./Classes/ABCardView.h - - - - ABImageView - NSImageView - - YES - - YES - copy: - cut: - delete: - paste: - - - YES - id - id - id - id - - - - YES - - YES - copy: - cut: - delete: - paste: - - - YES - - copy: - id - - - cut: - id - - - delete: - id - - - paste: - id - - - - - IBProjectSource - ./Classes/ABImageView.h - - - - DVTAutoLayoutView - NSView - - IBProjectSource - ./Classes/DVTAutoLayoutView.h - - - - DVTBorderedView - DVTAutoLayoutView - - contentView - NSView - - - contentView + window - contentView - NSView + window + NSWindow IBProjectSource - ./Classes/DVTBorderedView.h + ./Classes/AppDelegate.h - DVTDelayedMenuButton - NSButton - - IBProjectSource - ./Classes/DVTDelayedMenuButton.h - - - - DVTGradientImageButton - NSButton - - IBProjectSource - ./Classes/DVTGradientImageButton.h - - - - DVTImageAndTextCell - NSTextFieldCell - - IBProjectSource - ./Classes/DVTImageAndTextCell.h - - - - DVTImageAndTextColumn - NSTableColumn - - IBProjectSource - ./Classes/DVTImageAndTextColumn.h - - - - DVTOutlineView - NSOutlineView - - IBProjectSource - ./Classes/DVTOutlineView.h - - - - DVTSplitView - NSSplitView - - IBProjectSource - ./Classes/DVTSplitView.h - - - - DVTStackView - DVTAutoLayoutView - - IBProjectSource - ./Classes/DVTStackView.h - - - - DVTViewController - NSViewController - - IBProjectSource - ./Classes/DVTViewController.h - - - - HFController - NSObject - - selectAll: - id - - - selectAll: - - selectAll: - id - - - - IBProjectSource - ./Classes/HFController.h - - - - HFRepresenterTextView - NSView - - selectAll: - id - - - selectAll: - - selectAll: - id - - - - IBProjectSource - ./Classes/HFRepresenterTextView.h - - - - IBEditor - NSObject + NSDocument YES YES - changeFont: - selectAll: - sizeSelectionToFit: + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: YES id id id - - - - YES - - YES - changeFont: - selectAll: - sizeSelectionToFit: - - - YES - - changeFont: - id - - - selectAll: - id - - - sizeSelectionToFit: - id - - - - - IBProjectSource - ./Classes/IBEditor.h - - - - IDECapsuleListView - DVTStackView - - dataSource - id - - - dataSource - - dataSource - id - - - - IBProjectSource - ./Classes/IDECapsuleListView.h - - - - IDEDMArrayController - NSArrayController - - IBProjectSource - ./Classes/IDEDMArrayController.h - - - - IDEDMEditor - IDEEditor - - YES - - YES - bottomToolbarBorderView - sourceListSplitViewPane - sourceListViewController - splitView - - - YES - DVTBorderedView - NSView - IDEDMEditorSourceListController - DVTSplitView - - - - YES - - YES - bottomToolbarBorderView - sourceListSplitViewPane - sourceListViewController - splitView - - - YES - - bottomToolbarBorderView - DVTBorderedView - - - sourceListSplitViewPane - NSView - - - sourceListViewController - IDEDMEditorSourceListController - - - splitView - DVTSplitView - - - - - IBProjectSource - ./Classes/IDEDMEditor.h - - - - IDEDMEditorController - IDEViewController - - IBProjectSource - ./Classes/IDEDMEditorController.h - - - - IDEDMEditorSourceListController - IDEDMEditorController - - YES - - YES - borderedView - parentEditor - primaryColumn - sourceListOutlineView - sourceListTreeController - - - YES - DVTBorderedView - IDEDMEditor - DVTImageAndTextColumn - DVTOutlineView - NSTreeController - - - - YES - - YES - borderedView - parentEditor - primaryColumn - sourceListOutlineView - sourceListTreeController - - - YES - - borderedView - DVTBorderedView - - - parentEditor - IDEDMEditor - - - primaryColumn - DVTImageAndTextColumn - - - sourceListOutlineView - DVTOutlineView - - - sourceListTreeController - NSTreeController - - - - - IBProjectSource - ./Classes/IDEDMEditorSourceListController.h - - - - IDEDMHighlightImageAndTextCell - DVTImageAndTextCell - - IBProjectSource - ./Classes/IDEDMHighlightImageAndTextCell.h - - - - IDEDataModelBrowserEditor - IDEDMEditorController - - YES - - YES - attributesTableViewController - capsuleView - entityArrayController - fetchedPropertiesTableViewController - parentEditor - relationshipsTableViewController - - - YES - IDEDataModelPropertiesTableController - IDECapsuleListView - NSArrayController - IDEDataModelPropertiesTableController - IDEDataModelEntityContentsEditor - IDEDataModelPropertiesTableController - - - - YES - - YES - attributesTableViewController - capsuleView - entityArrayController - fetchedPropertiesTableViewController - parentEditor - relationshipsTableViewController - - - YES - - attributesTableViewController - IDEDataModelPropertiesTableController - - - capsuleView - IDECapsuleListView - - - entityArrayController - NSArrayController - - - fetchedPropertiesTableViewController - IDEDataModelPropertiesTableController - - - parentEditor - IDEDataModelEntityContentsEditor - - - relationshipsTableViewController - IDEDataModelPropertiesTableController - - - - - IBProjectSource - ./Classes/IDEDataModelBrowserEditor.h - - - - IDEDataModelConfigurationEditor - IDEDMEditorController - - YES - - YES - capsuleListView - parentEditor - tableController - - - YES - IDECapsuleListView - IDEDataModelEditor - IDEDataModelConfigurationTableController - - - - YES - - YES - capsuleListView - parentEditor - tableController - - - YES - - capsuleListView - IDECapsuleListView - - - parentEditor - IDEDataModelEditor - - - tableController - IDEDataModelConfigurationTableController - - - - - IBProjectSource - ./Classes/IDEDataModelConfigurationEditor.h - - - - IDEDataModelConfigurationTableController - IDEDMEditorController - - YES - - YES - configurationsArrayController - entitiesArrayController - parentEditor - tableView - - - YES - NSArrayController - NSArrayController - IDEDataModelConfigurationEditor - XDTableView - - - - YES - - YES - configurationsArrayController - entitiesArrayController - parentEditor - tableView - - - YES - - configurationsArrayController - NSArrayController - - - entitiesArrayController - NSArrayController - - - parentEditor - IDEDataModelConfigurationEditor - - - tableView - XDTableView - - - - - IBProjectSource - ./Classes/IDEDataModelConfigurationTableController.h - - - - IDEDataModelDiagramEditor - IDEDMEditorController - - YES - - YES - diagramView - parentEditor - - - YES - XDDiagramView - IDEDataModelEntityContentsEditor - - - - YES - - YES - diagramView - parentEditor - - - YES - - diagramView - XDDiagramView - - - parentEditor - IDEDataModelEntityContentsEditor - - - - - IBProjectSource - ./Classes/IDEDataModelDiagramEditor.h - - - - IDEDataModelEditor - IDEDMEditor - - YES - - YES - addEntityButton - addPropertyButton - browserDiagramSegmentControl - configurationViewController - entityContentsViewController - fetchRequestViewController - hierarchySegmentControl - tabView - - - YES - DVTDelayedMenuButton - DVTDelayedMenuButton - NSSegmentedControl - IDEDataModelConfigurationEditor - IDEDataModelEntityContentsEditor - IDEDataModelFetchRequestEditor - NSSegmentedControl - NSTabView - - - - YES - - YES - addEntityButton - addPropertyButton - browserDiagramSegmentControl - configurationViewController - entityContentsViewController - fetchRequestViewController - hierarchySegmentControl - tabView - - - YES - - addEntityButton - DVTDelayedMenuButton - - - addPropertyButton - DVTDelayedMenuButton - - - browserDiagramSegmentControl - NSSegmentedControl - - - configurationViewController - IDEDataModelConfigurationEditor - - - entityContentsViewController - IDEDataModelEntityContentsEditor - - - fetchRequestViewController - IDEDataModelFetchRequestEditor - - - hierarchySegmentControl - NSSegmentedControl - - - tabView - NSTabView - - - - - IBProjectSource - ./Classes/IDEDataModelEditor.h - - - - IDEDataModelEntityContentsEditor - IDEDMEditorController - - YES - - YES - browserViewController - diagramViewController - parentEditor - tabView - - - YES - IDEDataModelBrowserEditor - IDEDataModelDiagramEditor - IDEDataModelEditor - NSTabView - - - - YES - - YES - browserViewController - diagramViewController - parentEditor - tabView - - - YES - - browserViewController - IDEDataModelBrowserEditor - - - diagramViewController - IDEDataModelDiagramEditor - - - parentEditor - IDEDataModelEditor - - - tabView - NSTabView - - - - - IBProjectSource - ./Classes/IDEDataModelEntityContentsEditor.h - - - - IDEDataModelFetchRequestEditor - IDEDMEditorController - - YES - - YES - entityController - parentEditor - tableView - - - YES - NSArrayController - IDEDataModelEditor - IDECapsuleListView - - - - YES - - YES - entityController - parentEditor - tableView - - - YES - - entityController - NSArrayController - - - parentEditor - IDEDataModelEditor - - - tableView - IDECapsuleListView - - - - - IBProjectSource - ./Classes/IDEDataModelFetchRequestEditor.h - - - - IDEDataModelPropertiesTableController - IDEDMEditorController - - YES - - YES - arrayController - entitiesColumn - entityArrayController - parentEditor - propertyNameAndImageCell - tableView - - - YES - IDEDMArrayController - NSTableColumn - NSArrayController - IDEDataModelBrowserEditor - IDEDMHighlightImageAndTextCell - XDTableView - - - - YES - - YES - arrayController - entitiesColumn - entityArrayController - parentEditor - propertyNameAndImageCell - tableView - - - YES - - arrayController - IDEDMArrayController - - - entitiesColumn - NSTableColumn - - - entityArrayController - NSArrayController - - - parentEditor - IDEDataModelBrowserEditor - - - propertyNameAndImageCell - IDEDMHighlightImageAndTextCell - - - tableView - XDTableView - - - - - IBProjectSource - ./Classes/IDEDataModelPropertiesTableController.h - - - - IDEDocSetOutlineView - NSOutlineView - - IBProjectSource - ./Classes/IDEDocSetOutlineView.h - - - - IDEDocSetOutlineViewController - NSObject - - YES - - YES - getDocSetAction: - showProblemInfoForUpdate: - subscribeToPublisherAction: - unsubscribeFromPublisher: - updateDocSetAction: - - - YES - id - id - id - id - id - - - - YES - - YES - getDocSetAction: - showProblemInfoForUpdate: - subscribeToPublisherAction: - unsubscribeFromPublisher: - updateDocSetAction: - - - YES - - getDocSetAction: - id - - - showProblemInfoForUpdate: - id - - - subscribeToPublisherAction: - id - - - unsubscribeFromPublisher: - id - - - updateDocSetAction: - id - - - - - docSetOutlineView - IDEDocSetOutlineView - - - docSetOutlineView - - docSetOutlineView - IDEDocSetOutlineView - - - - IBProjectSource - ./Classes/IDEDocSetOutlineViewController.h - - - - IDEDocViewingPrefPaneController - IDEViewController - - YES - - YES - addSubscription: - checkForAndInstallUpdatesNow: - minimumFontSizeComboBoxAction: - minimumFontSizeEnabledAction: - showHelp: - showSubscriptionSheet: - subscriptionCancelAction: - toggleAutoCheckForAndInstallUpdates: - toggleDocSetInfo: - - - YES - id - id - id - id - id - id id id id @@ -4794,816 +3450,54 @@ YES YES - addSubscription: - checkForAndInstallUpdatesNow: - minimumFontSizeComboBoxAction: - minimumFontSizeEnabledAction: - showHelp: - showSubscriptionSheet: - subscriptionCancelAction: - toggleAutoCheckForAndInstallUpdates: - toggleDocSetInfo: + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: YES - addSubscription: + printDocument: id - checkForAndInstallUpdatesNow: + revertDocumentToSaved: id - minimumFontSizeComboBoxAction: + runPageLayout: id - minimumFontSizeEnabledAction: + saveDocument: id - showHelp: + saveDocumentAs: id - showSubscriptionSheet: - id - - - subscriptionCancelAction: - id - - - toggleAutoCheckForAndInstallUpdates: - id - - - toggleDocSetInfo: - id - - - - - YES - - YES - _addButton - _deleteButton - _showInfoAreaButton - _splitView - _splitViewDocSetInfoSubview - _splitViewDocSetsListSubview - borderedViewAroundSplitView - borderedViewBelowTable - checkAndInstallNowButton - docSetInfoTextView - docSetOutlineViewController - minimumFontSizeControl - noUpdatesAvailableMessage - showInfoButton - subscriptionTextField - subscriptionWindow - validateAddSubscriptionButton - - - YES - DVTGradientImageButton - DVTGradientImageButton - DVTGradientImageButton - NSSplitView - NSView - NSView - DVTBorderedView - DVTBorderedView - NSButton - NSTextView - IDEDocSetOutlineViewController - NSComboBox - NSTextField - NSButton - NSTextField - NSWindow - NSButton - - - - YES - - YES - _addButton - _deleteButton - _showInfoAreaButton - _splitView - _splitViewDocSetInfoSubview - _splitViewDocSetsListSubview - borderedViewAroundSplitView - borderedViewBelowTable - checkAndInstallNowButton - docSetInfoTextView - docSetOutlineViewController - minimumFontSizeControl - noUpdatesAvailableMessage - showInfoButton - subscriptionTextField - subscriptionWindow - validateAddSubscriptionButton - - - YES - - _addButton - DVTGradientImageButton - - - _deleteButton - DVTGradientImageButton - - - _showInfoAreaButton - DVTGradientImageButton - - - _splitView - NSSplitView - - - _splitViewDocSetInfoSubview - NSView - - - _splitViewDocSetsListSubview - NSView - - - borderedViewAroundSplitView - DVTBorderedView - - - borderedViewBelowTable - DVTBorderedView - - - checkAndInstallNowButton - NSButton - - - docSetInfoTextView - NSTextView - - - docSetOutlineViewController - IDEDocSetOutlineViewController - - - minimumFontSizeControl - NSComboBox - - - noUpdatesAvailableMessage - NSTextField - - - showInfoButton - NSButton - - - subscriptionTextField - NSTextField - - - subscriptionWindow - NSWindow - - - validateAddSubscriptionButton - NSButton - - - - - IBProjectSource - ./Classes/IDEDocViewingPrefPaneController.h - - - - IDEEditor - IDEViewController - - IBProjectSource - ./Classes/IDEEditor.h - - - - IDEViewController - DVTViewController - - IBProjectSource - ./Classes/IDEViewController.h - - - - IKImageView - - YES - - YES - copy: - crop: - cut: - paste: - - - YES - id - id - id - id - - - - YES - - YES - copy: - crop: - cut: - paste: - - - YES - - copy: - id - - - crop: - id - - - cut: - id - - - paste: + saveDocumentTo: id IBProjectSource - ./Classes/IKImageView.h - - - - QTMovieView - - YES - - YES - showAll: - showCustomButton: - toggleLoops: - zoomIn: - zoomOut: - - - YES - id - id - id - id - id - - - - YES - - YES - showAll: - showCustomButton: - toggleLoops: - zoomIn: - zoomOut: - - - YES - - showAll: - id - - - showCustomButton: - id - - - toggleLoops: - id - - - zoomIn: - id - - - zoomOut: - id - - - - - IBProjectSource - ./Classes/QTMovieView.h - - - - WebView - - YES - - YES - reloadFromOrigin: - resetPageZoom: - zoomPageIn: - zoomPageOut: - - - YES - id - id - id - id - - - - YES - - YES - reloadFromOrigin: - resetPageZoom: - zoomPageIn: - zoomPageOut: - - - YES - - reloadFromOrigin: - id - - - resetPageZoom: - id - - - zoomPageIn: - id - - - zoomPageOut: - id - - - - - IBProjectSource - ./Classes/WebView.h - - - - XDDiagramView - NSView - - YES - - YES - _graphLayouterMenuItemAction: - _zoomPopUpButtonAction: - alignBottomEdges: - alignCentersHorizontallyInContainer: - alignCentersVerticallyInContainer: - alignHorizontalCenters: - alignLeftEdges: - alignRightEdges: - alignTopEdges: - alignVerticalCenters: - bringToFront: - collapseAllCompartments: - copy: - cut: - delete: - deleteBackward: - deleteForward: - deselectAll: - diagramZoomIn: - diagramZoomOut: - expandAllCompartments: - flipHorizontally: - flipVertically: - layoutGraphicsConcentrically: - layoutGraphicsHierarchically: - lock: - makeSameHeight: - makeSameWidth: - moveDown: - moveDownAndModifySelection: - moveLeft: - moveLeftAndModifySelection: - moveRight: - moveRightAndModifySelection: - moveUp: - moveUpAndModifySelection: - paste: - rollDownAllCompartments: - rollUpAllCompartments: - selectAll: - sendToBack: - sizeToFit: - toggleGridShown: - toggleHiddenGraphicsShown: - togglePageBreaksShown: - toggleRuler: - toggleSnapsToGrid: - unlock: - - - YES - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - id - - - - YES - - YES - _graphLayouterMenuItemAction: - _zoomPopUpButtonAction: - alignBottomEdges: - alignCentersHorizontallyInContainer: - alignCentersVerticallyInContainer: - alignHorizontalCenters: - alignLeftEdges: - alignRightEdges: - alignTopEdges: - alignVerticalCenters: - bringToFront: - collapseAllCompartments: - copy: - cut: - delete: - deleteBackward: - deleteForward: - deselectAll: - diagramZoomIn: - diagramZoomOut: - expandAllCompartments: - flipHorizontally: - flipVertically: - layoutGraphicsConcentrically: - layoutGraphicsHierarchically: - lock: - makeSameHeight: - makeSameWidth: - moveDown: - moveDownAndModifySelection: - moveLeft: - moveLeftAndModifySelection: - moveRight: - moveRightAndModifySelection: - moveUp: - moveUpAndModifySelection: - paste: - rollDownAllCompartments: - rollUpAllCompartments: - selectAll: - sendToBack: - sizeToFit: - toggleGridShown: - toggleHiddenGraphicsShown: - togglePageBreaksShown: - toggleRuler: - toggleSnapsToGrid: - unlock: - - - YES - - _graphLayouterMenuItemAction: - id - - - _zoomPopUpButtonAction: - id - - - alignBottomEdges: - id - - - alignCentersHorizontallyInContainer: - id - - - alignCentersVerticallyInContainer: - id - - - alignHorizontalCenters: - id - - - alignLeftEdges: - id - - - alignRightEdges: - id - - - alignTopEdges: - id - - - alignVerticalCenters: - id - - - bringToFront: - id - - - collapseAllCompartments: - id - - - copy: - id - - - cut: - id - - - delete: - id - - - deleteBackward: - id - - - deleteForward: - id - - - deselectAll: - id - - - diagramZoomIn: - id - - - diagramZoomOut: - id - - - expandAllCompartments: - id - - - flipHorizontally: - id - - - flipVertically: - id - - - layoutGraphicsConcentrically: - id - - - layoutGraphicsHierarchically: - id - - - lock: - id - - - makeSameHeight: - id - - - makeSameWidth: - id - - - moveDown: - id - - - moveDownAndModifySelection: - id - - - moveLeft: - id - - - moveLeftAndModifySelection: - id - - - moveRight: - id - - - moveRightAndModifySelection: - id - - - moveUp: - id - - - moveUpAndModifySelection: - id - - - paste: - id - - - rollDownAllCompartments: - id - - - rollUpAllCompartments: - id - - - selectAll: - id - - - sendToBack: - id - - - sizeToFit: - id - - - toggleGridShown: - id - - - toggleHiddenGraphicsShown: - id - - - togglePageBreaksShown: - id - - - toggleRuler: - id - - - toggleSnapsToGrid: - id - - - unlock: - id - - - - - _diagramController - IDEDataModelDiagramEditor - - - _diagramController - - _diagramController - IDEDataModelDiagramEditor - - - - IBProjectSource - ./Classes/XDDiagramView.h - - - - XDTableView - NSTableView - - showAllTableColumns: - id - - - showAllTableColumns: - - showAllTableColumns: - id - - - - IBProjectSource - ./Classes/XDTableView.h - - - - AFNetworking_Mac_ExampleAppDelegate - NSObject - - YES - - YES - applicationShouldTerminate: - applicationWillFinishLaunching: - - - YES - id - id - - - - YES - - YES - applicationShouldTerminate: - applicationWillFinishLaunching: - - - YES - - applicationShouldTerminate: - id - - - applicationWillFinishLaunching: - id - - - - - IBProjectSource - ./Classes/AFNetworking_Mac_ExampleAppDelegate.h + ./Classes/NSDocument.h 0 IBCocoaFramework + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 From 5677b6de942d77f0978078dc1a6ec4ff45d5889c Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Fri, 23 Sep 2011 12:54:14 -0500 Subject: [PATCH 04/65] Adding AFNetworking workspace, containing both the iOS and Mac example applications Restructuring project files, directories, etc. --- .../project.pbxproj | 261 ++++++++++-------- .../AppDelegate.h | 0 .../AppDelegate.m | 0 .../{AFNetworking Mac Example => }/Info.plist | 0 .../{AFNetworking Mac Example => }/Prefix.pch | 0 .../Vendor/JSONKit/JSONKit.h | 0 .../Vendor/JSONKit/JSONKit.m | 0 .../Vendor/TTT/TTTLocationFormatter.h | 0 .../Vendor/TTT/TTTLocationFormatter.m | 0 .../en.lproj/Credits.rtf | 0 .../en.lproj/MainMenu.xib | 5 +- .../{AFNetworking Mac Example => }/main.m | 0 .../project.pbxproj | 31 +-- ...heme => AFNetworking iOS Example.xcscheme} | 29 +- .../xcschemes/xcschememanagement.plist | 2 +- 15 files changed, 169 insertions(+), 159 deletions(-) rename Mac Example/{AFNetworking Mac Example => }/AppDelegate.h (100%) rename Mac Example/{AFNetworking Mac Example => }/AppDelegate.m (100%) rename Mac Example/{AFNetworking Mac Example => }/Info.plist (100%) rename Mac Example/{AFNetworking Mac Example => }/Prefix.pch (100%) rename Mac Example/{AFNetworking Mac Example => }/Vendor/JSONKit/JSONKit.h (100%) rename Mac Example/{AFNetworking Mac Example => }/Vendor/JSONKit/JSONKit.m (100%) rename Mac Example/{AFNetworking Mac Example => }/Vendor/TTT/TTTLocationFormatter.h (100%) rename Mac Example/{AFNetworking Mac Example => }/Vendor/TTT/TTTLocationFormatter.m (100%) rename Mac Example/{AFNetworking Mac Example => }/en.lproj/Credits.rtf (100%) rename Mac Example/{AFNetworking Mac Example => }/en.lproj/MainMenu.xib (99%) rename Mac Example/{AFNetworking Mac Example => }/main.m (100%) rename iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/{AFNetworking Example.xcscheme => AFNetworking iOS Example.xcscheme} (72%) diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index 322df20..d320e92 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -7,51 +7,52 @@ objects = { /* Begin PBXBuildFile section */ - F8A27A2C142CF24700F5E0D6 /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A2D142CF24700F5E0D6 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A2E142CF24700F5E0D6 /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A23142CF24700F5E0D6 /* AFImageCache.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A2F142CF24700F5E0D6 /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A30142CF24700F5E0D6 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A31142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A32142CF24700F5E0D6 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27A3A142CF36100F5E0D6 /* JSONKit.m in Sources */ = {isa = PBXBuildFile; fileRef = F8A27A39142CF36100F5E0D6 /* JSONKit.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + 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"; }; }; + F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; + F8A27AC6142CFE1300F5E0D6 /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = F8A27AB1142CFE1300F5E0D6 /* Info.plist */; }; + 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 */; }; - F8CEEB7B142CEC6E00247B03 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB7A142CEC6E00247B03 /* main.m */; }; - F8CEEB7F142CEC6E00247B03 /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB7D142CEC6E00247B03 /* Credits.rtf */; }; - F8CEEB82142CEC6E00247B03 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8CEEB81142CEC6E00247B03 /* AppDelegate.m */; }; - F8CEEB85142CEC6E00247B03 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8CEEB83142CEC6E00247B03 /* MainMenu.xib */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ - F8A27A1E142CF24700F5E0D6 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = AFNetworking/AFHTTPClient.h; sourceTree = ""; }; - F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = AFNetworking/AFHTTPClient.m; sourceTree = ""; }; - F8A27A20142CF24700F5E0D6 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = AFNetworking/AFHTTPRequestOperation.h; sourceTree = ""; }; - F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; - F8A27A22142CF24700F5E0D6 /* AFImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageCache.h; path = AFNetworking/AFImageCache.h; sourceTree = ""; }; - F8A27A23142CF24700F5E0D6 /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = AFNetworking/AFImageCache.m; sourceTree = ""; }; - F8A27A24142CF24700F5E0D6 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageRequestOperation.h; path = AFNetworking/AFImageRequestOperation.h; sourceTree = ""; }; - F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = AFNetworking/AFImageRequestOperation.m; sourceTree = ""; }; - F8A27A26142CF24700F5E0D6 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFJSONRequestOperation.h; path = AFNetworking/AFJSONRequestOperation.h; sourceTree = ""; }; - F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFJSONRequestOperation.m; path = AFNetworking/AFJSONRequestOperation.m; sourceTree = ""; }; - F8A27A28142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = AFNetworking/AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; - F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = AFNetworking/AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; - F8A27A2A142CF24700F5E0D6 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; - F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; - F8A27A38142CF36100F5E0D6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; - F8A27A39142CF36100F5E0D6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; - F8A27A3B142CF75A00F5E0D6 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = AFNetworking/AFNetworking.h; sourceTree = ""; }; + F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPClient.h; sourceTree = ""; }; + F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClient.m; sourceTree = ""; }; + F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperation.h; sourceTree = ""; }; + F897DE6C142CFEDC000DDD35 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPRequestOperation.m; sourceTree = ""; }; + F897DE6D142CFEDC000DDD35 /* AFImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageCache.h; sourceTree = ""; }; + F897DE6E142CFEDC000DDD35 /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageCache.m; sourceTree = ""; }; + F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageRequestOperation.h; sourceTree = ""; }; + F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperation.m; sourceTree = ""; }; + F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFJSONRequestOperation.h; sourceTree = ""; }; + F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperation.m; sourceTree = ""; }; + F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; + F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; + F897DE75142CFEDC000DDD35 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = ""; }; + F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = ""; }; + F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = ""; }; + F8A27AB1142CFE1300F5E0D6 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F8A27AB2142CFE1300F5E0D6 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + F8A27AB3142CFE1300F5E0D6 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + F8A27ABA142CFE1300F5E0D6 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = en; path = Credits.rtf; sourceTree = ""; }; + F8A27ABC142CFE1300F5E0D6 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = MainMenu.xib; sourceTree = ""; }; + F8A27ABF142CFE1300F5E0D6 /* JSONKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSONKit.h; sourceTree = ""; }; + F8A27AC0142CFE1300F5E0D6 /* JSONKit.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = JSONKit.m; sourceTree = ""; }; + F8A27AC4142CFE1300F5E0D6 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; + F8A27AC5142CFE1300F5E0D6 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 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; }; - F8CEEB76142CEC6E00247B03 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - F8CEEB7A142CEC6E00247B03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - F8CEEB7C142CEC6E00247B03 /* Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; - F8CEEB7E142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = en; path = en.lproj/Credits.rtf; sourceTree = ""; }; - F8CEEB80142CEC6E00247B03 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - F8CEEB81142CEC6E00247B03 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - F8CEEB84142CEC6E00247B03 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/MainMenu.xib; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -66,21 +67,98 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - F8A27A37142CF36000F5E0D6 /* JSONKit */ = { + F897DE68142CFEDC000DDD35 /* AFNetworking */ = { isa = PBXGroup; children = ( - F8A27A38142CF36100F5E0D6 /* JSONKit.h */, - F8A27A39142CF36100F5E0D6 /* JSONKit.m */, + F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */, + F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */, + F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */, + F897DE6C142CFEDC000DDD35 /* AFHTTPRequestOperation.m */, + F897DE6D142CFEDC000DDD35 /* AFImageCache.h */, + F897DE6E142CFEDC000DDD35 /* AFImageCache.m */, + F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */, + F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */, + F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */, + F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */, + F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */, + F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */, + F897DE75142CFEDC000DDD35 /* AFNetworking.h */, + F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */, + F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */, ); - name = JSONKit; - path = "AFNetworking Mac Example/Vendor/JSONKit"; + name = AFNetworking; + path = ../../AFNetworking; + sourceTree = ""; + }; + F8A27AB4142CFE1300F5E0D6 /* Classes */ = { + isa = PBXGroup; + children = ( + F8A27AB5142CFE1300F5E0D6 /* Controllers */, + F8A27AB6142CFE1300F5E0D6 /* Models */, + F8A27AB7142CFE1300F5E0D6 /* Views */, + ); + path = Classes; + sourceTree = ""; + }; + F8A27AB5142CFE1300F5E0D6 /* Controllers */ = { + isa = PBXGroup; + children = ( + ); + path = Controllers; + sourceTree = ""; + }; + F8A27AB6142CFE1300F5E0D6 /* Models */ = { + isa = PBXGroup; + children = ( + ); + path = Models; + sourceTree = ""; + }; + F8A27AB7142CFE1300F5E0D6 /* Views */ = { + isa = PBXGroup; + children = ( + ); + path = Views; + sourceTree = ""; + }; + F8A27ABD142CFE1300F5E0D6 /* Vendor */ = { + isa = PBXGroup; + children = ( + F897DE68142CFEDC000DDD35 /* AFNetworking */, + F8A27ABE142CFE1300F5E0D6 /* JSONKit */, + ); + path = Vendor; + sourceTree = ""; + }; + F8A27ABE142CFE1300F5E0D6 /* JSONKit */ = { + isa = PBXGroup; + children = ( + F8A27ABF142CFE1300F5E0D6 /* JSONKit.h */, + F8A27AC0142CFE1300F5E0D6 /* JSONKit.m */, + ); + path = JSONKit; + sourceTree = ""; + }; + 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 */, + ); + name = "Supporting Files"; sourceTree = ""; }; F8CEEB5F142CEC6E00247B03 = { isa = PBXGroup; children = ( - F8CEEB74142CEC6E00247B03 /* AFNetworking Mac Example */, - F8CEEB8B142CECAA00247B03 /* Vendor */, + F8A27AB4142CFE1300F5E0D6 /* Classes */, + F8A27ACD142CFE3000F5E0D6 /* Supporting Files */, + F8A27ABD142CFE1300F5E0D6 /* Vendor */, F8CEEB6D142CEC6E00247B03 /* Frameworks */, F8CEEB6B142CEC6E00247B03 /* Products */, ); @@ -113,60 +191,6 @@ name = "Other Frameworks"; sourceTree = ""; }; - F8CEEB74142CEC6E00247B03 /* AFNetworking Mac Example */ = { - isa = PBXGroup; - children = ( - F8CEEB80142CEC6E00247B03 /* AppDelegate.h */, - F8CEEB81142CEC6E00247B03 /* AppDelegate.m */, - F8CEEB83142CEC6E00247B03 /* MainMenu.xib */, - F8CEEB75142CEC6E00247B03 /* Supporting Files */, - ); - path = "AFNetworking Mac Example"; - sourceTree = ""; - }; - F8CEEB75142CEC6E00247B03 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - F8CEEB76142CEC6E00247B03 /* Info.plist */, - F8CEEB7A142CEC6E00247B03 /* main.m */, - F8CEEB7C142CEC6E00247B03 /* Prefix.pch */, - F8CEEB7D142CEC6E00247B03 /* Credits.rtf */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - F8CEEB8B142CECAA00247B03 /* Vendor */ = { - isa = PBXGroup; - children = ( - F8A27A37142CF36000F5E0D6 /* JSONKit */, - F8CEEB8C142CED6F00247B03 /* AFNetworking */, - ); - name = Vendor; - sourceTree = ""; - }; - F8CEEB8C142CED6F00247B03 /* AFNetworking */ = { - isa = PBXGroup; - children = ( - F8A27A3B142CF75A00F5E0D6 /* AFNetworking.h */, - F8A27A20142CF24700F5E0D6 /* AFHTTPRequestOperation.h */, - F8A27A21142CF24700F5E0D6 /* AFHTTPRequestOperation.m */, - F8A27A26142CF24700F5E0D6 /* AFJSONRequestOperation.h */, - F8A27A27142CF24700F5E0D6 /* AFJSONRequestOperation.m */, - F8A27A1E142CF24700F5E0D6 /* AFHTTPClient.h */, - F8A27A1F142CF24700F5E0D6 /* AFHTTPClient.m */, - F8A27A22142CF24700F5E0D6 /* AFImageCache.h */, - F8A27A23142CF24700F5E0D6 /* AFImageCache.m */, - F8A27A24142CF24700F5E0D6 /* AFImageRequestOperation.h */, - F8A27A25142CF24700F5E0D6 /* AFImageRequestOperation.m */, - F8A27A28142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.h */, - F8A27A29142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m */, - F8A27A2A142CF24700F5E0D6 /* UIImageView+AFNetworking.h */, - F8A27A2B142CF24700F5E0D6 /* UIImageView+AFNetworking.m */, - ); - name = AFNetworking; - path = ../../AFNetworking; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -218,8 +242,9 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - F8CEEB7F142CEC6E00247B03 /* Credits.rtf in Resources */, - F8CEEB85142CEC6E00247B03 /* MainMenu.xib in Resources */, + F8A27AC6142CFE1300F5E0D6 /* Info.plist in Resources */, + F8A27AC9142CFE1300F5E0D6 /* Credits.rtf in Resources */, + F8A27ACA142CFE1300F5E0D6 /* MainMenu.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -230,36 +255,38 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - F8CEEB7B142CEC6E00247B03 /* main.m in Sources */, - F8CEEB82142CEC6E00247B03 /* AppDelegate.m in Sources */, - F8A27A2C142CF24700F5E0D6 /* AFHTTPClient.m in Sources */, - F8A27A2D142CF24700F5E0D6 /* AFHTTPRequestOperation.m in Sources */, - F8A27A2E142CF24700F5E0D6 /* AFImageCache.m in Sources */, - F8A27A2F142CF24700F5E0D6 /* AFImageRequestOperation.m in Sources */, - F8A27A30142CF24700F5E0D6 /* AFJSONRequestOperation.m in Sources */, - F8A27A31142CF24700F5E0D6 /* AFNetworkActivityIndicatorManager.m in Sources */, - F8A27A32142CF24700F5E0D6 /* UIImageView+AFNetworking.m in Sources */, - F8A27A3A142CF36100F5E0D6 /* JSONKit.m in Sources */, + 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 */, + F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */, + F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ - F8CEEB7D142CEC6E00247B03 /* Credits.rtf */ = { + F8A27AB9142CFE1300F5E0D6 /* Credits.rtf */ = { isa = PBXVariantGroup; children = ( - F8CEEB7E142CEC6E00247B03 /* en */, + F8A27ABA142CFE1300F5E0D6 /* en */, ); name = Credits.rtf; + path = en.lproj; sourceTree = ""; }; - F8CEEB83142CEC6E00247B03 /* MainMenu.xib */ = { + F8A27ABB142CFE1300F5E0D6 /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( - F8CEEB84142CEC6E00247B03 /* en */, + F8A27ABC142CFE1300F5E0D6 /* en */, ); name = MainMenu.xib; + path = en.lproj; sourceTree = ""; }; /* End PBXVariantGroup section */ @@ -316,8 +343,8 @@ isa = XCBuildConfiguration; buildSettings = { GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "AFNetworking Mac Example/Prefix.pch"; - INFOPLIST_FILE = "AFNetworking Mac Example/Info.plist"; + GCC_PREFIX_HEADER = Prefix.pch; + INFOPLIST_FILE = Info.plist; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; @@ -327,8 +354,8 @@ isa = XCBuildConfiguration; buildSettings = { GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "AFNetworking Mac Example/Prefix.pch"; - INFOPLIST_FILE = "AFNetworking Mac Example/Info.plist"; + GCC_PREFIX_HEADER = Prefix.pch; + INFOPLIST_FILE = Info.plist; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; diff --git a/Mac Example/AFNetworking Mac Example/AppDelegate.h b/Mac Example/AppDelegate.h similarity index 100% rename from Mac Example/AFNetworking Mac Example/AppDelegate.h rename to Mac Example/AppDelegate.h diff --git a/Mac Example/AFNetworking Mac Example/AppDelegate.m b/Mac Example/AppDelegate.m similarity index 100% rename from Mac Example/AFNetworking Mac Example/AppDelegate.m rename to Mac Example/AppDelegate.m diff --git a/Mac Example/AFNetworking Mac Example/Info.plist b/Mac Example/Info.plist similarity index 100% rename from Mac Example/AFNetworking Mac Example/Info.plist rename to Mac Example/Info.plist diff --git a/Mac Example/AFNetworking Mac Example/Prefix.pch b/Mac Example/Prefix.pch similarity index 100% rename from Mac Example/AFNetworking Mac Example/Prefix.pch rename to Mac Example/Prefix.pch diff --git a/Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.h b/Mac Example/Vendor/JSONKit/JSONKit.h similarity index 100% rename from Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.h rename to Mac Example/Vendor/JSONKit/JSONKit.h diff --git a/Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.m b/Mac Example/Vendor/JSONKit/JSONKit.m similarity index 100% rename from Mac Example/AFNetworking Mac Example/Vendor/JSONKit/JSONKit.m rename to Mac Example/Vendor/JSONKit/JSONKit.m diff --git a/Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.h b/Mac Example/Vendor/TTT/TTTLocationFormatter.h similarity index 100% rename from Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.h rename to Mac Example/Vendor/TTT/TTTLocationFormatter.h diff --git a/Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.m b/Mac Example/Vendor/TTT/TTTLocationFormatter.m similarity index 100% rename from Mac Example/AFNetworking Mac Example/Vendor/TTT/TTTLocationFormatter.m rename to Mac Example/Vendor/TTT/TTTLocationFormatter.m diff --git a/Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf b/Mac Example/en.lproj/Credits.rtf similarity index 100% rename from Mac Example/AFNetworking Mac Example/en.lproj/Credits.rtf rename to Mac Example/en.lproj/Credits.rtf diff --git a/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib b/Mac Example/en.lproj/MainMenu.xib similarity index 99% rename from Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib rename to Mac Example/en.lproj/MainMenu.xib index ed5f98c..e525305 100644 --- a/Mac Example/AFNetworking Mac Example/en.lproj/MainMenu.xib +++ b/Mac Example/en.lproj/MainMenu.xib @@ -1324,12 +1324,9 @@ - + 256 {480, 360} - - - {{0, 0}, {1920, 1178}} {10000000000000, 10000000000000} diff --git a/Mac Example/AFNetworking Mac Example/main.m b/Mac Example/main.m similarity index 100% rename from Mac Example/AFNetworking Mac Example/main.m rename to Mac Example/main.m diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj index 4da83fc..43e0111 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj @@ -15,7 +15,6 @@ F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5D013E0AA6500B28E3E /* UIImageView+AFNetworking.m */; }; F8D25D191396A9D300CF3BD6 /* placeholder-stamp.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D171396A9D300CF3BD6 /* placeholder-stamp.png */; }; F8D25D1A1396A9D300CF3BD6 /* placeholder-stamp@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = F8D25D181396A9D300CF3BD6 /* placeholder-stamp@2x.png */; }; - F8DA09D21396ABED0057D0CC /* AFGowallaAPIClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */; }; F8DA09D41396ABED0057D0CC /* NearbySpotsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = F8DA09C81396AB690057D0CC /* NearbySpotsViewController.m */; }; F8DA09D51396ABED0057D0CC /* Spot.m in Sources */ = {isa = PBXBuildFile; fileRef = F8DA09CB1396AB690057D0CC /* Spot.m */; }; F8DA09D61396ABED0057D0CC /* SpotTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = F8DA09CE1396AB690057D0CC /* SpotTableViewCell.m */; }; @@ -50,8 +49,6 @@ F8D25D141396A9C400CF3BD6 /* TTTLocationFormatter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TTTLocationFormatter.m; sourceTree = ""; }; F8D25D171396A9D300CF3BD6 /* placeholder-stamp.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "placeholder-stamp.png"; path = "Images/placeholder-stamp.png"; sourceTree = SOURCE_ROOT; }; 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 = ""; }; - F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFGowallaAPIClient.m; path = Classes/AFGowallaAPIClient.m; sourceTree = ""; }; F8DA09C71396AB690057D0CC /* NearbySpotsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NearbySpotsViewController.h; sourceTree = ""; }; F8DA09C81396AB690057D0CC /* NearbySpotsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NearbySpotsViewController.m; sourceTree = ""; }; F8DA09CA1396AB690057D0CC /* Spot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Spot.h; sourceTree = ""; }; @@ -62,7 +59,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,7 +68,7 @@ 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; }; F8E469E413957E0400DB05C8 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; - F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = ""; }; + F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = ""; }; F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = ""; }; FF2B770C140DAC4E00A8DEC2 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; /* End PBXFileReference section */ @@ -154,7 +151,6 @@ F8E469551395739C00DB05C8 = { isa = PBXGroup; children = ( - F8E469B71395759C00DB05C8 /* Networking Extensions */, F8E4696A1395739D00DB05C8 /* Classes */, F8E469ED1395812A00DB05C8 /* Images */, F8E469931395743A00DB05C8 /* Vendor */, @@ -166,7 +162,7 @@ F8E469611395739C00DB05C8 /* Products */ = { isa = PBXGroup; children = ( - F8E469601395739C00DB05C8 /* AFNetworkingExample.app */, + F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */, ); name = Products; sourceTree = ""; @@ -189,6 +185,7 @@ F8E4696A1395739D00DB05C8 /* Classes */ = { isa = PBXGroup; children = ( + F8E469B71395759C00DB05C8 /* Networking Extensions */, F8DA09C61396AB690057D0CC /* Controllers */, F8DA09C91396AB690057D0CC /* Models */, F8DA09CC1396AB690057D0CC /* Views */, @@ -243,10 +240,9 @@ F8E469B71395759C00DB05C8 /* Networking Extensions */ = { isa = PBXGroup; children = ( - F8D25D1B1396A9DE00CF3BD6 /* AFGowallaAPIClient.h */, - F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */, ); name = "Networking Extensions"; + path = ..; sourceTree = ""; }; F8E469ED1395812A00DB05C8 /* Images */ = { @@ -262,9 +258,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 */, @@ -274,9 +270,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 */ @@ -288,7 +284,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; @@ -300,7 +296,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - F8E4695F1395739C00DB05C8 /* AFNetworkingExample */, + F8E4695F1395739C00DB05C8 /* AFNetworking iOS Example */, ); }; /* End PBXProject section */ @@ -322,7 +318,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - F8DA09D21396ABED0057D0CC /* AFGowallaAPIClient.m in Sources */, F8DA09D41396ABED0057D0CC /* NearbySpotsViewController.m in Sources */, F8DA09D51396ABED0057D0CC /* Spot.m in Sources */, F8DA09D61396ABED0057D0CC /* SpotTableViewCell.m in Sources */, @@ -406,7 +401,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 */, @@ -415,7 +410,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 */, diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme similarity index 72% rename from iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme rename to iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme index a8639b4..dc62418 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking Example.xcscheme +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme @@ -1,6 +1,6 @@ + version = "1.3"> @@ -14,9 +14,9 @@ + BuildableName = "AFNetworking iOS Example.app" + BlueprintName = "AFNetworking iOS Example" + ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj"> @@ -32,8 +32,6 @@ + BuildableName = "AFNetworking iOS Example.app" + BlueprintName = "AFNetworking iOS Example" + ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj"> - - + BuildableName = "AFNetworking iOS Example.app" + BlueprintName = "AFNetworking iOS Example" + ReferencedContainer = "container:AFNetworking iOS Example.xcodeproj"> diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist index 223ec1d..4e24393 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -4,7 +4,7 @@ SchemeUserState - AFNetworking Example.xcscheme + AFNetworking iOS Example.xcscheme orderHint 1 From 561df45eb76fcc1377056cc87616adfa070f6470 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 4 Oct 2011 00:13:12 -0500 Subject: [PATCH 05/65] Initial working implementation of new candidate class structure --- AFNetworking/AFHTTPClient.m | 4 +- AFNetworking/AFHTTPRequestOperation.h | 102 +---- AFNetworking/AFHTTPRequestOperation.m | 395 +++--------------- AFNetworking/AFImageRequestOperation.h | 14 +- AFNetworking/AFImageRequestOperation.m | 47 ++- AFNetworking/AFJSONRequestOperation.h | 68 +-- AFNetworking/AFJSONRequestOperation.m | 132 +++--- .../AFNetworkActivityIndicatorManager.m | 4 +- AFNetworking/AFURLConnectionOperation.h | 97 +++++ AFNetworking/AFURLConnectionOperation.m | 368 ++++++++++++++++ AFNetworking/UIImageView+AFNetworking.m | 2 +- .../project.pbxproj | 6 + 12 files changed, 656 insertions(+), 583 deletions(-) create mode 100644 AFNetworking/AFURLConnectionOperation.h create mode 100644 AFNetworking/AFURLConnectionOperation.m diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 0c828c6..b2b5041 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -228,11 +228,11 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { - AFJSONRequestOperation *operation = [AFJSONRequestOperation operationWithRequest:urlRequest success:^(id JSON) { + AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) { if (success) { success(JSON); } - } failure:^(NSHTTPURLResponse *response, NSError *error) { + } failure:^(__unused NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { if (failure) { failure(response, error); } diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 0823a48..283753b 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -21,26 +21,10 @@ // THE SOFTWARE. #import +#import "AFURLConnectionOperation.h" /** - Indicates an error occured in AFNetworking. - - @discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain. - */ -extern NSString * const AFNetworkingErrorDomain; - -/** - Posted when an operation begins executing. - */ -extern NSString * const AFHTTPOperationDidStartNotification; - -/** - Posted when an operation finishes. - */ -extern NSString * const AFHTTPOperationDidFinishNotification; - -/** - `AFHTTPRequestOperation` is an `NSOperation` that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. + `AFHTTPRequestOperation` is an `NSOperation` subclass that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. # Subclassing Notes @@ -50,7 +34,7 @@ extern NSString * const AFHTTPOperationDidFinishNotification; ## Methods to Subclass - Unless you need to override specific `NSURLConnection` delegate methods, you shouldn't need to subclass any methods. Instead, you should provide alternative constructor class methods, that are essentially wrappers around the callback from `AFHTTPRequestOperation`. + // ### `NSURLConnection` Delegate Methods @@ -70,82 +54,42 @@ extern NSString * const AFHTTPOperationDidFinishNotification; @see NSOperation @see NSURLConnection */ -@interface AFHTTPRequestOperation : NSOperation { -@private - NSSet *_runLoopModes; - - NSURLConnection *_connection; - NSURLRequest *_request; - NSHTTPURLResponse *_response; - NSError *_error; - - NSData *_responseBody; - NSInteger _totalBytesRead; - NSMutableData *_dataAccumulator; - NSOutputStream *_outputStream; +@interface AFHTTPRequestOperation : AFURLConnectionOperation { +@private + NSIndexSet *_acceptableStatusCodes; + NSSet *_acceptableContentTypes; } -@property (nonatomic, retain) NSSet *runLoopModes; - -@property (readonly, nonatomic, retain) NSURLRequest *request; @property (readonly, nonatomic, retain) NSHTTPURLResponse *response; -@property (readonly, nonatomic, retain) NSError *error; -@property (readonly, nonatomic, retain) NSData *responseBody; -@property (readonly) NSString *responseString; +/** + Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) used in operationWithRequest:success and operationWithRequest:success:failure. + + By default, this is the range 200 to 299, inclusive. + */ +@property (nonatomic, retain) NSIndexSet *acceptableStatusCodes; +@property (nonatomic, retain) NSSet *acceptableContentTypes; ///--------------------------------------- /// @name Creating HTTP Request Operations ///--------------------------------------- -/** - Creates and returns an `AFHTTPRequestOperation` object and sets the specified completion callback. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation. - @param completion A block object to be executed when the HTTP request operation is finished. This block has no return value and takes four arguments: the request sent from the client, the response received from the server, the HTTP body received by the server during the execution of the request, and an error, which will have been set if an error occured while loading the request. - - @return A new HTTP request operation - */ -+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion; ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +///------------------------------- +/// @name Validating HTTP Response +///------------------------------- /** - Creates and returns a streaming `AFHTTPRequestOperation` object and sets the specified input stream, output stream, and completion callback. - @param urlRequest The request object to be loaded asynchronously during execution of the operation. - @param inputStream The input stream object for reading data to be sent during the request. If set, the input stream is set as the `HTTPBodyStream` on the `NSMutableURLRequest`. If the request method is `GET`, it is changed to `POST`. This argument may be `nil`. - @param outputStream The output stream object for writing data received during the request. If set, data accumulated in `NSURLConnectionDelegate` methods will be sent to the output stream, and the NSData parameter in the completion block will be `nil`. This argument may be `nil`. - @param completion A block object to be executed when the HTTP request operation is finished. This block has no return value and takes four arguments: the request sent from the client, the response received from the server, the data received by the server during the execution of the request, and an error, which will have been set if an error occured while loading the request. This argument may be `nil`. - - @see operationWithRequest:completion - - @return A new streaming HTTP request operation */ -+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest - inputStream:(NSInputStream *)inputStream - outputStream:(NSOutputStream *)outputStream - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion; - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- +- (BOOL)hasAcceptableStatusCode; /** - Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. - @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times. - - @see setDownloadProgressBlock */ -- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block; - -/** - Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. - - @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes read since the last time the upload progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times. - - @see setUploadProgressBlock - */ -- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block; +- (BOOL)hasAcceptableContentType; @end diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index f0b05aa..dee3043 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -22,381 +22,86 @@ #import "AFHTTPRequestOperation.h" -static NSUInteger const kAFHTTPMinimumInitialDataCapacity = 1024; -static NSUInteger const kAFHTTPMaximumInitialDataCapacity = 1024 * 1024 * 8; - -typedef enum { - AFHTTPOperationReadyState = 1, - AFHTTPOperationExecutingState = 2, - AFHTTPOperationFinishedState = 3, - AFHTTPOperationCancelledState = 4, -} AFHTTPOperationState; - -NSString * const AFNetworkingErrorDomain = @"com.alamofire.networking.error"; - -NSString * const AFHTTPOperationDidStartNotification = @"com.alamofire.networking.http-operation.start"; -NSString * const AFHTTPOperationDidFinishNotification = @"com.alamofire.networking.http-operation.finish"; - -typedef void (^AFHTTPRequestOperationProgressBlock)(NSInteger bytes, NSInteger totalBytes, NSInteger totalBytesExpected); -typedef void (^AFHTTPRequestOperationCompletionBlock)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error); - -static inline NSString * AFKeyPathFromOperationState(AFHTTPOperationState state) { - switch (state) { - case AFHTTPOperationReadyState: - return @"isReady"; - case AFHTTPOperationExecutingState: - return @"isExecuting"; - case AFHTTPOperationFinishedState: - return @"isFinished"; - default: - return @"state"; - } -} - -static inline BOOL AFHTTPOperationStateTransitionIsValid(AFHTTPOperationState from, AFHTTPOperationState to) { - switch (from) { - case AFHTTPOperationReadyState: - switch (to) { - case AFHTTPOperationExecutingState: - return YES; - default: - return NO; - } - case AFHTTPOperationExecutingState: - switch (to) { - case AFHTTPOperationReadyState: - return NO; - default: - return YES; - } - case AFHTTPOperationFinishedState: - return NO; - default: - return YES; - } -} - @interface AFHTTPRequestOperation () -@property (readwrite, nonatomic, assign) AFHTTPOperationState state; -@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; -@property (readwrite, nonatomic, retain) NSURLConnection *connection; -@property (readwrite, nonatomic, retain) NSURLRequest *request; -@property (readwrite, nonatomic, retain) NSHTTPURLResponse *response; @property (readwrite, nonatomic, retain) NSError *error; -@property (readwrite, nonatomic, retain) NSData *responseBody; -@property (readwrite, nonatomic, assign) NSInteger totalBytesRead; -@property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator; -@property (readwrite, nonatomic, retain) NSOutputStream *outputStream; -@property (readwrite, nonatomic, copy) AFHTTPRequestOperationProgressBlock uploadProgress; -@property (readwrite, nonatomic, copy) AFHTTPRequestOperationProgressBlock downloadProgress; -@property (readwrite, nonatomic, copy) AFHTTPRequestOperationCompletionBlock completion; - -- (void)operationDidStart; -- (void)finish; @end @implementation AFHTTPRequestOperation -@synthesize state = _state; -@synthesize cancelled = _cancelled; -@synthesize connection = _connection; -@synthesize runLoopModes = _runLoopModes; -@synthesize request = _request; -@synthesize response = _response; -@synthesize error = _error; -@synthesize responseBody = _responseBody; -@synthesize totalBytesRead = _totalBytesRead; -@synthesize dataAccumulator = _dataAccumulator; -@synthesize outputStream = _outputStream; -@synthesize uploadProgress = _uploadProgress; -@synthesize downloadProgress = _downloadProgress; -@synthesize completion = _completion; +@dynamic error; +@dynamic response; +@synthesize acceptableStatusCodes = _acceptableStatusCodes; +@synthesize acceptableContentTypes = _acceptableContentTypes; -static NSThread *_networkRequestThread = nil; - -+ (void)networkRequestThreadEntryPoint:(id)__unused object { - do { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - [[NSRunLoop currentRunLoop] run]; - [pool drain]; - } while (YES); -} - -+ (NSThread *)networkRequestThread { - static dispatch_once_t oncePredicate; - - dispatch_once(&oncePredicate, ^{ - _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; - [_networkRequestThread start]; - }); - - return _networkRequestThread; -} - -+ (AFHTTPRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error))completion ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - AFHTTPRequestOperation *operation = [[[self alloc] init] autorelease]; - operation.request = urlRequest; - operation.completion = completion; + AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; + operation.completionBlock = ^ { + if (operation.error) { + if (failure) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.request, operation.response, operation.error); + }); + } + } else { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, operation.responseBody); + }); + } + } + }; return operation; } -+ (AFHTTPRequestOperation *)streamingOperationWithRequest:(NSURLRequest *)urlRequest - inputStream:(NSInputStream *)inputStream - outputStream:(NSOutputStream *)outputStream - completion:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))completion -{ - NSMutableURLRequest *mutableURLRequest = [[urlRequest mutableCopy] autorelease]; - if (inputStream) { - [mutableURLRequest setHTTPBodyStream:inputStream]; - if ([[mutableURLRequest HTTPMethod] isEqualToString:@"GET"]) { - [mutableURLRequest setHTTPMethod:@"POST"]; - } - } - - AFHTTPRequestOperation *operation = [self operationWithRequest:mutableURLRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, __unused NSData *data, NSError *error) { - if (completion) { - completion(request, response, error); - } - }]; - - operation.outputStream = outputStream; - - return operation; -} - -- (id)init { - self = [super init]; +- (id)initWithRequest:(NSURLRequest *)request { + self = [super initWithRequest:request]; if (!self) { - return nil; + return nil; } - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - self.state = AFHTTPOperationReadyState; - + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + return self; } - (void)dealloc { - [_runLoopModes release]; - - [_request release]; - [_response release]; - [_responseBody release]; - [_dataAccumulator release]; - [_outputStream release]; _outputStream = nil; - - [_connection release]; _connection = nil; - - [_uploadProgress release]; - [_downloadProgress release]; - [_completion release]; + [_acceptableStatusCodes release]; [super dealloc]; } -- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block { - self.uploadProgress = block; +- (NSHTTPURLResponse *)response { + return (NSHTTPURLResponse *)[super response]; } -- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setState:(AFHTTPOperationState)state { - if (self.state == state) { - return; - } - - if (!AFHTTPOperationStateTransitionIsValid(self.state, state)) { - return; - } - - NSString *oldStateKey = AFKeyPathFromOperationState(self.state); - NSString *newStateKey = AFKeyPathFromOperationState(state); - - [self willChangeValueForKey:newStateKey]; - [self willChangeValueForKey:oldStateKey]; - _state = state; - [self didChangeValueForKey:oldStateKey]; - [self didChangeValueForKey:newStateKey]; - - switch (state) { - case AFHTTPOperationExecutingState: - [[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidStartNotification object:self]; - break; - case AFHTTPOperationFinishedState: - [[NSNotificationCenter defaultCenter] postNotificationName:AFHTTPOperationDidFinishNotification object:self]; - break; - default: - break; - } -} - -- (void)setCancelled:(BOOL)cancelled { - [self willChangeValueForKey:@"isCancelled"]; - _cancelled = cancelled; - [self didChangeValueForKey:@"isCancelled"]; - - if ([self isCancelled]) { - self.state = AFHTTPOperationFinishedState; - } -} - -- (NSString *)responseString { - if (!self.response || !self.responseBody) { - return nil; - } - - NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName)); - - return [[[NSString alloc] initWithData:self.responseBody encoding:textEncoding] autorelease]; -} - -#pragma mark - NSOperation - -- (BOOL)isReady { - return self.state == AFHTTPOperationReadyState; -} - -- (BOOL)isExecuting { - return self.state == AFHTTPOperationExecutingState; -} - -- (BOOL)isFinished { - return self.state == AFHTTPOperationFinishedState; -} - -- (BOOL)isConcurrent { - return YES; -} - -- (void)start { - if (![self isReady]) { - return; - } - - self.state = AFHTTPOperationExecutingState; - - [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]]; -} - -- (void)operationDidStart { - self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - for (NSString *runLoopMode in self.runLoopModes) { - [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; - [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; - } - - [self.connection start]; -} - -- (void)cancel { - if ([self isFinished]) { - return; - } - - [super cancel]; - - self.cancelled = YES; - - [self.connection cancel]; -} - -- (void)finish { - self.state = AFHTTPOperationFinishedState; - - if ([self isCancelled]) { - return; - } - - if (self.completion) { - self.completion(self.request, self.response, self.responseBody, self.error); - } -} - -#pragma mark - NSURLConnection - -- (void)connection:(NSURLConnection *)__unused connection -didReceiveResponse:(NSURLResponse *)response -{ - self.response = (NSHTTPURLResponse *)response; - - if (self.outputStream) { - [self.outputStream open]; - } else { - - NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), kAFHTTPMinimumInitialDataCapacity); - NSUInteger capacity = MIN(maxCapacity, kAFHTTPMaximumInitialDataCapacity); - self.dataAccumulator = [NSMutableData dataWithCapacity:capacity]; - } -} - -- (void)connection:(NSURLConnection *)__unused connection - didReceiveData:(NSData *)data -{ - self.totalBytesRead += [data length]; - - if (self.outputStream) { - if ([self.outputStream hasSpaceAvailable]) { - const uint8_t *dataBuffer = [data bytes]; - [self.outputStream write:&dataBuffer[0] maxLength:[data length]]; +- (NSError *)error { + if (self.response && ![super error]) { + if (![self hasAcceptableStatusCode]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), self.acceptableStatusCodes, [self.response statusCode]] forKey:NSLocalizedDescriptionKey]; + [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + + self.error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease]; + } else if (![self hasAcceptableContentType]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), self.acceptableContentTypes, [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; + [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + + self.error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease]; } - } else { - [self.dataAccumulator appendData:data]; } - if (self.downloadProgress) { - self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength); - } + return [super error]; } -- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection { - if (self.outputStream) { - [self.outputStream close]; - } else { - self.responseBody = [NSData dataWithData:self.dataAccumulator]; - [_dataAccumulator release]; _dataAccumulator = nil; - } - - [self finish]; +- (BOOL)hasAcceptableStatusCode { + return !self.acceptableStatusCodes || [self.acceptableStatusCodes containsIndex:[self.response statusCode]]; } -- (void)connection:(NSURLConnection *)__unused connection - didFailWithError:(NSError *)error -{ - self.error = error; - - if (self.outputStream) { - [self.outputStream close]; - } else { - [_dataAccumulator release]; _dataAccumulator = nil; - } - - [self finish]; -} - -- (void)connection:(NSURLConnection *)__unused connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - if (self.uploadProgress) { - self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection - willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - if ([self isCancelled]) { - return nil; - } - - return cachedResponse; +- (BOOL)hasAcceptableContentType { + return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]]; } @end diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 77760a5..8639bfc 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -40,8 +40,8 @@ @return A new image request operation */ -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success; ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(UIImage *image))success; /** Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. @@ -54,10 +54,10 @@ @return A new image request operation */ -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock - cacheName:(NSString *)cacheNameOrNil - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock + cacheName:(NSString *)cacheNameOrNil + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 0e4d702..097acd8 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -26,7 +26,7 @@ static dispatch_queue_t af_image_request_operation_processing_queue; static dispatch_queue_t image_request_operation_processing_queue() { if (af_image_request_operation_processing_queue == NULL) { - af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.image-request.processing", 0); + af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0); } return af_image_request_operation_processing_queue; @@ -34,38 +34,40 @@ static dispatch_queue_t image_request_operation_processing_queue() { @implementation AFImageRequestOperation -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(UIImage *image))success { - return [self operationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { + return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { if (success) { success(image); } } failure:nil]; } -+ (AFImageRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock cacheName:(NSString *)cacheNameOrNil success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - return (AFImageRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { + AFImageRequestOperation *operation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease]; + + operation.completionBlock = ^ { dispatch_async(image_request_operation_processing_queue(), ^(void) { - if (error) { + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { - failure(request, response, error); + failure(operation.request, operation.response, operation.error); }); } } else { - UIImage *image = nil; + UIImage *image = nil; if ([[UIScreen mainScreen] scale] == 2.0) { - CGImageRef imageRef = [[UIImage imageWithData:data] CGImage]; + CGImageRef imageRef = [[UIImage imageWithData:operation.responseBody] CGImage]; image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; } else { - image = [UIImage imageWithData:data]; - } + image = [UIImage imageWithData:operation.responseBody]; + } if (imageProcessingBlock) { image = imageProcessingBlock(image); @@ -73,16 +75,29 @@ static dispatch_queue_t image_request_operation_processing_queue() { dispatch_async(dispatch_get_main_queue(), ^(void) { if (success) { - success(request, response, image); + success(operation.request, operation.response, image); } }); - if ([request cachePolicy] != NSURLCacheStorageNotAllowed) { - [[AFImageCache sharedImageCache] cacheImage:image forURL:[request URL] cacheName:cacheNameOrNil]; + if ([operation.request cachePolicy] != NSURLCacheStorageNotAllowed) { + [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil]; } } }); - }]; + }; + + return operation; +} + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/bmp", @"image/x-xbitmap", nil]; + + return self; } @end diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index 91e47dc..96b890f 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -29,44 +29,18 @@ @see NSOperation @see AFHTTPRequestOperation */ -@interface AFJSONRequestOperation : AFHTTPRequestOperation +@interface AFJSONRequestOperation : AFHTTPRequestOperation { +@private + id _responseJSON; +} + +@property (readonly, nonatomic, retain) id responseJSON; + ///--------------------------------------- /// @name Creating JSON Request Operations ///--------------------------------------- -/** - Creates and returns an `AFJSONRequestOperation` object and sets the specified success callback. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the JSON request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is the JSON object created from the response data of request, or nil if there was an error. - - @see defaultAcceptableStatusCodes - @see defaultAcceptableContentTypes - @see operationWithRequest:success:failure: - - @return A new JSON request operation - */ -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id JSON))success; - -/** - Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the JSON request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is the JSON object created from the response data of request. - @param failure A block object to be executed when the JSON request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a two arguments: the response from the server, and the error describing the network or parsing error that occurred. - - @see defaultAcceptableStatusCodes - @see defaultAcceptableContentTypes - @see operationWithRequest:success: - - @return A new JSON request operation - */ -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id JSON))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; - /** Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks, as well as the status codes and content types that are acceptable for a successful request. @@ -78,29 +52,7 @@ @return A new JSON request operation */ -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes - acceptableContentTypes:(NSSet *)acceptableContentTypes - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; - - -///---------------------------------- -/// @name Getting Default HTTP Values -///---------------------------------- - -/** - Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) used in operationWithRequest:success and operationWithRequest:success:failure. - - By default, this is the range 200 to 299, inclusive. - */ -+ (NSIndexSet *)defaultAcceptableStatusCodes; - -/** - Returns an `NSSet` object containing the acceptable HTTP content type (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17) used in operationWithRequest:success and operationWithRequest:success:failure. - - By default, this contains `application/json`, `application/x-javascript`, `text/javascript`, `text/x-javascript`, `text/x-json`, `text/json`, and `text/plain` - */ -+ (NSSet *)defaultAcceptableContentTypes; - ++ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; @end diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 2698a08..5ba411b 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -28,108 +28,94 @@ static dispatch_queue_t af_json_request_operation_processing_queue; static dispatch_queue_t json_request_operation_processing_queue() { if (af_json_request_operation_processing_queue == NULL) { - af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.json-request.processing", 0); + af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0); } return af_json_request_operation_processing_queue; } +@interface AFJSONRequestOperation () +@property (readwrite, nonatomic, retain) id responseJSON; + ++ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; +@end + @implementation AFJSONRequestOperation +@synthesize responseJSON = _responseJSON; -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id JSON))success -{ - return [self operationWithRequest:urlRequest success:success failure:nil]; ++ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { + id JSON = nil; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 + if ([NSJSONSerialization class]) { + JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:error]; + } else { + JSON = [[JSONDecoder decoder] objectWithData:data error:error]; + } +#else + JSON = [[JSONDecoder decoder] objectWithData:data error:error]; +#endif + + return JSON; } -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id JSON))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure -{ - return [self operationWithRequest:urlRequest acceptableStatusCodes:[self defaultAcceptableStatusCodes] acceptableContentTypes:[self defaultAcceptableContentTypes] success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) { - if (success) { - success(JSON); - } - } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) { - if (failure) { - failure(response, error); - } - }]; -} - -+ (AFJSONRequestOperation *)operationWithRequest:(NSURLRequest *)urlRequest - acceptableStatusCodes:(NSIndexSet *)acceptableStatusCodes - acceptableContentTypes:(NSSet *)acceptableContentTypes - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure ++ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - return (AFJSONRequestOperation *)[self operationWithRequest:urlRequest completion:^(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data, NSError *error) { - if (!error) { - if (acceptableStatusCodes && ![acceptableStatusCodes containsIndex:[response statusCode]]) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), acceptableStatusCodes, [response statusCode]] forKey:NSLocalizedDescriptionKey]; - [userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey]; - - error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo] autorelease]; - } - - if (acceptableContentTypes && ![acceptableContentTypes containsObject:[response MIMEType]]) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), acceptableContentTypes, [response MIMEType]] forKey:NSLocalizedDescriptionKey]; - [userInfo setValue:[request URL] forKey:NSURLErrorFailingURLErrorKey]; - - error = [[[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo] autorelease]; - } - } - - if (error) { + AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; + operation.completionBlock = ^ { + if (operation.error) { if (failure) { - dispatch_async(dispatch_get_main_queue(), ^{ - failure(request, response, error); - }); - } - } else if ([data length] == 0) { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^{ - success(request, response, nil); + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.request, operation.response, operation.error); }); } } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { - id JSON = nil; - NSError *JSONError = nil; -#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 - if ([NSJSONSerialization class]) { - JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&JSONError]; - } else { - JSON = [[JSONDecoder decoder] objectWithData:data error:&JSONError]; - } -#else - JSON = [[JSONDecoder decoder] objectWithData:data error:&JSONError]; -#endif + NSError *error = nil; + id JSON = [self JSONObjectWithData:operation.responseBody error:&error]; dispatch_async(dispatch_get_main_queue(), ^(void) { - if (JSONError) { + if (error) { if (failure) { - failure(request, response, JSONError); + failure(operation.request, operation.response, error); } } else { if (success) { - success(request, response, JSON); + success(operation.request, operation.response, JSON); } } - }); + }); }); } - }]; + }; + + return operation; } -+ (NSIndexSet *)defaultAcceptableStatusCodes { - return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; + + return self; } -+ (NSSet *)defaultAcceptableContentTypes { - return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; +- (void)dealloc { + [_responseJSON release]; + [super dealloc]; +} + +- (id)responseJSON { + if (!_responseJSON && self.response && self.responseBody) { + self.responseJSON = [[self class] JSONObjectWithData:self.responseBody error:nil]; + } + + return _responseJSON; } @end diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index efd8d34..7094ea6 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -48,8 +48,8 @@ return nil; } - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFHTTPOperationDidStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFHTTPOperationDidFinishNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; return self; } diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h new file mode 100644 index 0000000..56847d1 --- /dev/null +++ b/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1,97 @@ +// AFURLConnectionOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +/** + Indicates an error occured in AFNetworking. + + @discussion Error codes for AFNetworkingErrorDomain correspond to codes in NSURLErrorDomain. + */ +extern NSString * const AFNetworkingErrorDomain; + +/** + Posted when an operation begins executing. + */ +extern NSString * const AFNetworkingOperationDidStartNotification; + +/** + Posted when an operation finishes. + */ +extern NSString * const AFNetworkingOperationDidFinishNotification; + + +@interface AFURLConnectionOperation : NSOperation { +@private + NSSet *_runLoopModes; + + NSURLConnection *_connection; + NSURLRequest *_request; + NSHTTPURLResponse *_response; + NSError *_error; + + NSData *_responseBody; + NSInteger _totalBytesRead; + NSMutableData *_dataAccumulator; + NSOutputStream *_outputStream; +} + +@property (nonatomic, retain) NSSet *runLoopModes; + +@property (readonly, nonatomic, retain) NSURLRequest *request; +@property (readonly, nonatomic, retain) NSURLResponse *response; +@property (readonly, nonatomic, retain) NSError *error; + +@property (readonly, nonatomic, retain) NSData *responseBody; +@property (readonly, nonatomic, copy) NSString *responseString; + +@property (nonatomic, retain) NSInputStream *inputStream; +@property (nonatomic, retain) NSOutputStream *outputStream; + +/** + @discussion This is the designated initializer. + */ +- (id)initWithRequest:(NSURLRequest *)urlRequest; + +///--------------------------------- +/// @name Setting Progress Callbacks +///--------------------------------- + +/** + Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times. + + @see setDownloadProgressBlock + */ +- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block; + +/** + Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes read since the last time the upload progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times. + + @see setUploadProgressBlock + */ +- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block; + +@end \ No newline at end of file diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m new file mode 100644 index 0000000..0dfda3e --- /dev/null +++ b/AFNetworking/AFURLConnectionOperation.m @@ -0,0 +1,368 @@ +// AFURLConnectionOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLConnectionOperation.h" + +static NSUInteger const kAFHTTPMinimumInitialDataCapacity = 1024; +static NSUInteger const kAFHTTPMaximumInitialDataCapacity = 1024 * 1024 * 8; + +typedef enum { + AFHTTPOperationReadyState = 1, + AFHTTPOperationExecutingState = 2, + AFHTTPOperationFinishedState = 3, +} AFOperationState; + +NSString * const AFNetworkingErrorDomain = @"com.alamofire.networking.error"; + +NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; +NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; + +typedef void (^AFURLConnectionOperationProgressBlock)(NSInteger bytes, NSInteger totalBytes, NSInteger totalBytesExpected); + +static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { + switch (state) { + case AFHTTPOperationReadyState: + return @"isReady"; + case AFHTTPOperationExecutingState: + return @"isExecuting"; + case AFHTTPOperationFinishedState: + return @"isFinished"; + default: + return @"state"; + } +} + +static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOperationState to) { + switch (from) { + case AFHTTPOperationReadyState: + switch (to) { + case AFHTTPOperationExecutingState: + return YES; + default: + return NO; + } + case AFHTTPOperationExecutingState: + switch (to) { + case AFHTTPOperationReadyState: + return NO; + default: + return YES; + } + case AFHTTPOperationFinishedState: + return NO; + default: + return YES; + } +} + +@interface AFURLConnectionOperation () +@property (readwrite, nonatomic, assign) AFOperationState state; +@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; +@property (readwrite, nonatomic, retain) NSURLConnection *connection; +@property (readwrite, nonatomic, retain) NSURLRequest *request; +@property (readwrite, nonatomic, retain) NSURLResponse *response; +@property (readwrite, nonatomic, retain) NSError *error; +@property (readwrite, nonatomic, retain) NSData *responseBody; +@property (readwrite, nonatomic, copy) NSString *responseString; +@property (readwrite, nonatomic, assign) NSInteger totalBytesRead; +@property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; + +- (void)operationDidStart; +- (void)finish; +@end + +@implementation AFURLConnectionOperation +@synthesize state = _state; +@synthesize cancelled = _cancelled; +@synthesize connection = _connection; +@synthesize runLoopModes = _runLoopModes; +@synthesize request = _request; +@synthesize response = _response; +@synthesize error = _error; +@synthesize responseBody = _responseBody; +@synthesize responseString = _responseString; +@synthesize totalBytesRead = _totalBytesRead; +@synthesize dataAccumulator = _dataAccumulator; +@dynamic inputStream; +@synthesize outputStream = _outputStream; +@synthesize uploadProgress = _uploadProgress; +@synthesize downloadProgress = _downloadProgress; + ++ (void)networkRequestThreadEntryPoint:(id)__unused object { + do { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + [[NSRunLoop currentRunLoop] run]; + [pool drain]; + } while (YES); +} + ++ (NSThread *)networkRequestThread { + static NSThread *_networkRequestThread = nil; + static dispatch_once_t oncePredicate; + + dispatch_once(&oncePredicate, ^{ + _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; + [_networkRequestThread start]; + }); + + return _networkRequestThread; +} + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + + self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; + + self.state = AFHTTPOperationReadyState; + + return self; +} + +- (void)dealloc { + [_runLoopModes release]; + + [_request release]; + [_response release]; + [_error release]; + + [_responseBody release]; + [_responseString release]; + [_dataAccumulator release]; + [_outputStream release]; _outputStream = nil; + + [_connection release]; _connection = nil; + + [_uploadProgress release]; + [_downloadProgress release]; + + [super dealloc]; +} + +- (NSInputStream *)inputStream { + return self.request.HTTPBodyStream; +} + +- (void)setInputStream:(NSInputStream *)inputStream { + if (inputStream) { + NSMutableURLRequest *mutableRequest = [[self.request mutableCopy] autorelease]; + mutableRequest.HTTPBodyStream = inputStream; + self.request = mutableRequest; + } +} + +- (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block { + self.uploadProgress = block; +} + +- (void)setDownloadProgressBlock:(void (^)(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead))block { + self.downloadProgress = block; +} + +- (void)setState:(AFOperationState)state { + if (self.state == state) { + return; + } + + if (!AFOperationStateTransitionIsValid(self.state, state)) { + return; + } + + NSString *oldStateKey = AFKeyPathFromOperationState(self.state); + NSString *newStateKey = AFKeyPathFromOperationState(state); + + [self willChangeValueForKey:newStateKey]; + [self willChangeValueForKey:oldStateKey]; + _state = state; + [self didChangeValueForKey:oldStateKey]; + [self didChangeValueForKey:newStateKey]; + + switch (state) { + case AFHTTPOperationExecutingState: + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; + break; + case AFHTTPOperationFinishedState: + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; + break; + default: + break; + } +} + +- (void)setCancelled:(BOOL)cancelled { + [self willChangeValueForKey:@"isCancelled"]; + _cancelled = cancelled; + [self didChangeValueForKey:@"isCancelled"]; + + if ([self isCancelled]) { + self.state = AFHTTPOperationFinishedState; + } +} + +- (NSString *)responseString { + if (!_responseString && self.response && self.responseBody) { + NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName)); + self.responseString = [[[NSString alloc] initWithData:self.responseBody encoding:textEncoding] autorelease]; + } + + return _responseString; +} + +#pragma mark - NSOperation + +- (BOOL)isReady { + return self.state == AFHTTPOperationReadyState; +} + +- (BOOL)isExecuting { + return self.state == AFHTTPOperationExecutingState; +} + +- (BOOL)isFinished { + return self.state == AFHTTPOperationFinishedState; +} + +- (BOOL)isConcurrent { + return YES; +} + +- (void)start { + if (![self isReady]) { + return; + } + + self.state = AFHTTPOperationExecutingState; + + [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:YES modes:[self.runLoopModes allObjects]]; +} + +- (void)operationDidStart { + self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease]; + + NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; + for (NSString *runLoopMode in self.runLoopModes) { + [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; + [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; + } + + [self.connection start]; +} + +- (void)cancel { + [super cancel]; + + self.cancelled = YES; + + [self.connection cancel]; +} + +- (void)finish { + self.state = AFHTTPOperationFinishedState; +} + +#pragma mark - NSURLConnectionDelegate + +- (void)connection:(NSURLConnection *)__unused connection + didSendBodyData:(NSInteger)bytesWritten + totalBytesWritten:(NSInteger)totalBytesWritten +totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite +{ + if (self.uploadProgress) { + self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)connection:(NSURLConnection *)__unused connection +didReceiveResponse:(NSURLResponse *)response +{ + self.response = (NSHTTPURLResponse *)response; + + if (self.outputStream) { + [self.outputStream open]; + } else { + NSUInteger maxCapacity = MAX((NSUInteger)llabs(response.expectedContentLength), kAFHTTPMinimumInitialDataCapacity); + NSUInteger capacity = MIN(maxCapacity, kAFHTTPMaximumInitialDataCapacity); + self.dataAccumulator = [NSMutableData dataWithCapacity:capacity]; + } +} + +- (void)connection:(NSURLConnection *)__unused connection + didReceiveData:(NSData *)data +{ + self.totalBytesRead += [data length]; + + if (self.outputStream) { + if ([self.outputStream hasSpaceAvailable]) { + const uint8_t *dataBuffer = [data bytes]; + [self.outputStream write:&dataBuffer[0] maxLength:[data length]]; + } + } else { + [self.dataAccumulator appendData:data]; + } + + if (self.downloadProgress) { + self.downloadProgress([data length], self.totalBytesRead, (NSInteger)self.response.expectedContentLength); + } +} + +- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection { + if (self.outputStream) { + [self.outputStream close]; + } else { + self.responseBody = [NSData dataWithData:self.dataAccumulator]; + [_dataAccumulator release]; _dataAccumulator = nil; + } + + [self finish]; +} + +- (void)connection:(NSURLConnection *)__unused connection + didFailWithError:(NSError *)error +{ + self.error = error; + + if (self.outputStream) { + [self.outputStream close]; + } else { + [_dataAccumulator release]; _dataAccumulator = nil; + } + + [self finish]; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)__unused connection + willCacheResponse:(NSCachedURLResponse *)cachedResponse +{ + if ([self isCancelled]) { + return nil; + } + + return cachedResponse; +} + +@end diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index 6e128dc..6d0a10e 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -97,7 +97,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { self.image = placeholderImage; - self.af_imageRequestOperation = [AFImageRequestOperation operationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { + self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) { dispatch_async(dispatch_get_main_queue(), ^{ if (success) { diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index f91b2df..198fb15 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */; }; F874B5D913E0AA6500B28E3E /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */; }; F874B5DA13E0AA6500B28E3E /* AFImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CA13E0AA6500B28E3E /* AFImageCache.m */; }; F874B5DB13E0AA6500B28E3E /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */; }; @@ -33,6 +34,8 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = ../AFNetworking/AFURLConnectionOperation.h; sourceTree = ""; }; + F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = ""; }; F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; F874B5CA13E0AA6500B28E3E /* AFImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageCache.m; path = ../AFNetworking/AFImageCache.m; sourceTree = ""; }; F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = ""; }; @@ -221,6 +224,8 @@ F8E469941395744600DB05C8 /* AFNetworking */ = { isa = PBXGroup; children = ( + F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */, + F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */, F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */, F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, @@ -335,6 +340,7 @@ F874B5DD13E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.m in Sources */, F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */, F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */, + F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From b85c59516d7309a2ca78a095e731a35a4d9da521 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 4 Oct 2011 00:41:32 -0500 Subject: [PATCH 06/65] Don't execute completion block if cancelled --- AFNetworking/AFHTTPRequestOperation.m | 4 ++++ AFNetworking/AFImageRequestOperation.m | 4 ++++ AFNetworking/AFURLConnectionOperation.m | 6 +++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index dee3043..422cd1f 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -38,6 +38,10 @@ { AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 097acd8..70bfd59 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -53,6 +53,10 @@ static dispatch_queue_t image_request_operation_processing_queue() { AFImageRequestOperation *operation = [[[AFImageRequestOperation alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + dispatch_async(image_request_operation_processing_queue(), ^(void) { if (operation.error) { if (failure) { diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 0dfda3e..9a97541 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -274,6 +274,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)cancel { + if ([self isFinished]) { + return; + } + [super cancel]; self.cancelled = YES; @@ -282,7 +286,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)finish { - self.state = AFHTTPOperationFinishedState; + self.state = AFHTTPOperationFinishedState; } #pragma mark - NSURLConnectionDelegate From c0cba6748a9fbb6d201ef4637c35dc67ab0fae16 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 11:26:51 -0500 Subject: [PATCH 07/65] Refactoring state transition logic for AFURLConnectionOperation --- AFNetworking/AFURLConnectionOperation.m | 66 ++++++++++++------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 9a97541..8500a33 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -51,29 +51,6 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } } -static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOperationState to) { - switch (from) { - case AFHTTPOperationReadyState: - switch (to) { - case AFHTTPOperationExecutingState: - return YES; - default: - return NO; - } - case AFHTTPOperationExecutingState: - switch (to) { - case AFHTTPOperationReadyState: - return NO; - default: - return YES; - } - case AFHTTPOperationFinishedState: - return NO; - default: - return YES; - } -} - @interface AFURLConnectionOperation () @property (readwrite, nonatomic, assign) AFOperationState state; @property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; @@ -88,6 +65,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; +- (BOOL)shouldTransitionToState:(AFOperationState)state; - (void)operationDidStart; - (void)finish; @end @@ -135,10 +113,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp return nil; } - self.request = urlRequest; - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; + self.request = urlRequest; + self.state = AFHTTPOperationReadyState; return self; @@ -185,11 +163,7 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } - (void)setState:(AFOperationState)state { - if (self.state == state) { - return; - } - - if (!AFOperationStateTransitionIsValid(self.state, state)) { + if (![self shouldTransitionToState:state]) { return; } @@ -214,6 +188,30 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp } } +- (BOOL)shouldTransitionToState:(AFOperationState)state { + switch (self.state) { + case AFHTTPOperationReadyState: + switch (state) { + case AFHTTPOperationExecutingState: + return YES; + case AFHTTPOperationFinishedState: + return [self isCancelled]; + default: + return NO; + } + case AFHTTPOperationExecutingState: + switch (state) { + case AFHTTPOperationFinishedState: + return YES; + default: + return NO; + } + case AFHTTPOperationFinishedState: + default: + return NO; + } +} + - (void)setCancelled:(BOOL)cancelled { [self willChangeValueForKey:@"isCancelled"]; _cancelled = cancelled; @@ -273,6 +271,10 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp [self.connection start]; } +- (void)finish { + self.state = AFHTTPOperationFinishedState; +} + - (void)cancel { if ([self isFinished]) { return; @@ -285,10 +287,6 @@ static inline BOOL AFOperationStateTransitionIsValid(AFOperationState from, AFOp [self.connection cancel]; } -- (void)finish { - self.state = AFHTTPOperationFinishedState; -} - #pragma mark - NSURLConnectionDelegate - (void)connection:(NSURLConnection *)__unused connection From ccdc5f2d9b98db81c3063e9dfa85de8ea0b51e4d Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:36:45 -0500 Subject: [PATCH 08/65] Approaching a reasonable design for restructuring AFHTTPRequestOperation and subclasses --- AFNetworking/AFHTTPClient.h | 7 ++-- AFNetworking/AFHTTPClient.m | 14 +++---- AFNetworking/AFHTTPRequestOperation.h | 6 +++ AFNetworking/AFHTTPRequestOperation.m | 7 ++-- AFNetworking/AFImageRequestOperation.h | 7 +++- AFNetworking/AFImageRequestOperation.m | 51 +++++++++++++++++++------ AFNetworking/AFJSONRequestOperation.h | 4 +- AFNetworking/AFJSONRequestOperation.m | 19 ++++++--- AFNetworking/AFURLConnectionOperation.h | 2 +- AFNetworking/AFURLConnectionOperation.m | 13 ++++--- 10 files changed, 89 insertions(+), 41 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 7ac8177..c095d28 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -183,9 +183,9 @@ @param success A block object to be executed when the request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `application/json`). This block has no return value and takes a single argument, which is an object created from the response data of request. @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the resonse data as JSON. This block has no return value and takes a single argument, which is the `NSError` object describing the network or parsing error that occurred. */ -- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)request - success:(void (^)(id object))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; +- (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; ///--------------------------------- /// @name Cancelling HTTP Operations @@ -322,3 +322,4 @@ */ - (void)appendString:(NSString *)string; @end + diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index b2b5041..05f989a 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -224,9 +224,9 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS return request; } -- (void)enqueueHTTPOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id object))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +- (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) { if (success) { @@ -257,7 +257,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters]; - [self enqueueHTTPOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure]; } - (void)postPath:(NSString *)path @@ -266,7 +266,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters]; - [self enqueueHTTPOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure]; } - (void)putPath:(NSString *)path @@ -275,7 +275,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters]; - [self enqueueHTTPOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure]; } - (void)deletePath:(NSString *)path @@ -284,7 +284,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters]; - [self enqueueHTTPOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperationWithRequest:request success:success failure:failure]; } @end diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 283753b..714c1a4 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -23,6 +23,11 @@ #import #import "AFURLConnectionOperation.h" +@protocol AFHTTPClientRequestOperation ++ (BOOL)canInitWithRequest:(NSURLRequest *)request; ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; +@end + /** `AFHTTPRequestOperation` is an `NSOperation` subclass that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. @@ -58,6 +63,7 @@ @private NSIndexSet *_acceptableStatusCodes; NSSet *_acceptableContentTypes; + NSError *_HTTPError; } @property (readonly, nonatomic, retain) NSHTTPURLResponse *response; diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 422cd1f..5e8bd60 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -27,10 +27,9 @@ @end @implementation AFHTTPRequestOperation -@dynamic error; -@dynamic response; @synthesize acceptableStatusCodes = _acceptableStatusCodes; @synthesize acceptableContentTypes = _acceptableContentTypes; +@synthesize error = _HTTPError; + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success @@ -51,7 +50,7 @@ } else { if (success) { dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, operation.responseBody); + success(operation.request, operation.response, operation.responseData); }); } } @@ -81,7 +80,7 @@ } - (NSError *)error { - if (self.response && ![super error]) { + if (self.response) { if (![self hasAcceptableStatusCode]) { NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code %@, got %d", nil), self.acceptableStatusCodes, [self.response statusCode]] forKey:NSLocalizedDescriptionKey]; diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 8639bfc..b7ee9bb 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -30,7 +30,12 @@ @see NSOperation @see AFHTTPRequestOperation */ -@interface AFImageRequestOperation : AFHTTPRequestOperation +@interface AFImageRequestOperation : AFHTTPRequestOperation { +@private + UIImage *_responseImage; +} + +@property (readonly, nonatomic, retain) UIImage *responseImage; /** Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 70bfd59..a1062b4 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -32,7 +32,26 @@ static dispatch_queue_t image_request_operation_processing_queue() { return af_image_request_operation_processing_queue; } +@interface AFImageRequestOperation () +@property (readwrite, nonatomic, retain) UIImage *responseImage; + ++ (UIImage *)imageWithData:(NSData *)data error:(NSError **)error ; +@end + @implementation AFImageRequestOperation +@synthesize responseImage = _responseImage; + ++ (UIImage *)imageWithData:(NSData *)data error:(NSError **)__unused error { + UIImage *image = nil; + if ([[UIScreen mainScreen] scale] == 2.0) { + CGImageRef imageRef = [[UIImage imageWithData:data] CGImage]; + image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; + } else { + image = [UIImage imageWithData:data]; + } + + return image; +} + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success @@ -64,24 +83,19 @@ static dispatch_queue_t image_request_operation_processing_queue() { failure(operation.request, operation.response, operation.error); }); } - } else { - UIImage *image = nil; - if ([[UIScreen mainScreen] scale] == 2.0) { - CGImageRef imageRef = [[UIImage imageWithData:operation.responseBody] CGImage]; - image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; - } else { - image = [UIImage imageWithData:operation.responseBody]; - } + } else { + UIImage *image = [[self class] imageWithData:operation.responseData error:nil]; if (imageProcessingBlock) { image = imageProcessingBlock(image); } - dispatch_async(dispatch_get_main_queue(), ^(void) { - if (success) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, image); - } - }); + }); + } if ([operation.request cachePolicy] != NSURLCacheStorageNotAllowed) { [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil]; @@ -104,4 +118,17 @@ static dispatch_queue_t image_request_operation_processing_queue() { return self; } +- (void)dealloc { + [_responseImage release]; + [super dealloc]; +} + +- (UIImage *)responseImage { + if (!_responseImage && [self isFinished]) { + self.responseImage = [[self class] imageWithData:self.responseData error:nil]; + } + + return _responseImage; +} + @end diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index 96b890f..08d1aee 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -31,12 +31,12 @@ */ @interface AFJSONRequestOperation : AFHTTPRequestOperation { @private - id _responseJSON; + id _responseJSON; + NSError *_JSONError; } @property (readonly, nonatomic, retain) id responseJSON; - ///--------------------------------------- /// @name Creating JSON Request Operations ///--------------------------------------- diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 5ba411b..a820212 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -36,12 +36,14 @@ static dispatch_queue_t json_request_operation_processing_queue() { @interface AFJSONRequestOperation () @property (readwrite, nonatomic, retain) id responseJSON; +@property (readwrite, nonatomic, retain) NSError *error; + (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; @end @implementation AFJSONRequestOperation @synthesize responseJSON = _responseJSON; +@synthesize error = _JSONError; + (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { id JSON = nil; @@ -55,7 +57,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { #else JSON = [[JSONDecoder decoder] objectWithData:data error:error]; #endif - + return JSON; } @@ -65,6 +67,10 @@ static dispatch_queue_t json_request_operation_processing_queue() { { AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + if (operation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { @@ -74,10 +80,11 @@ static dispatch_queue_t json_request_operation_processing_queue() { } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { NSError *error = nil; - id JSON = [self JSONObjectWithData:operation.responseBody error:&error]; + id JSON = [self JSONObjectWithData:operation.responseData error:&error]; + operation.error = error; dispatch_async(dispatch_get_main_queue(), ^(void) { - if (error) { + if (operation.error) { if (failure) { failure(operation.request, operation.response, error); } @@ -111,8 +118,10 @@ static dispatch_queue_t json_request_operation_processing_queue() { } - (id)responseJSON { - if (!_responseJSON && self.response && self.responseBody) { - self.responseJSON = [[self class] JSONObjectWithData:self.responseBody error:nil]; + if (!_responseJSON && [self isFinished]) { + NSError *error = nil; + self.responseJSON = [[self class] JSONObjectWithData:self.responseData error:nil]; + self.error = error; } return _responseJSON; diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 56847d1..9c7ba9a 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -61,7 +61,7 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; @property (readonly, nonatomic, retain) NSURLResponse *response; @property (readonly, nonatomic, retain) NSError *error; -@property (readonly, nonatomic, retain) NSData *responseBody; +@property (readonly, nonatomic, retain) NSData *responseData; @property (readonly, nonatomic, copy) NSString *responseString; @property (nonatomic, retain) NSInputStream *inputStream; diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8500a33..8540ad1 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -58,7 +58,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @property (readwrite, nonatomic, retain) NSURLRequest *request; @property (readwrite, nonatomic, retain) NSURLResponse *response; @property (readwrite, nonatomic, retain) NSError *error; -@property (readwrite, nonatomic, retain) NSData *responseBody; +@property (readwrite, nonatomic, retain) NSData *responseData; @property (readwrite, nonatomic, copy) NSString *responseString; @property (readwrite, nonatomic, assign) NSInteger totalBytesRead; @property (readwrite, nonatomic, retain) NSMutableData *dataAccumulator; @@ -78,7 +78,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @synthesize request = _request; @synthesize response = _response; @synthesize error = _error; -@synthesize responseBody = _responseBody; +@synthesize responseData = _responseBody; @synthesize responseString = _responseString; @synthesize totalBytesRead = _totalBytesRead; @synthesize dataAccumulator = _dataAccumulator; @@ -207,8 +207,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { return NO; } case AFHTTPOperationFinishedState: - default: return NO; + default: + return YES; } } @@ -223,9 +224,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } - (NSString *)responseString { - if (!_responseString && self.response && self.responseBody) { + if (!_responseString && self.response && self.responseData) { NSStringEncoding textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)self.response.textEncodingName)); - self.responseString = [[[NSString alloc] initWithData:self.responseBody encoding:textEncoding] autorelease]; + self.responseString = [[[NSString alloc] initWithData:self.responseData encoding:textEncoding] autorelease]; } return _responseString; @@ -336,7 +337,7 @@ didReceiveResponse:(NSURLResponse *)response if (self.outputStream) { [self.outputStream close]; } else { - self.responseBody = [NSData dataWithData:self.dataAccumulator]; + self.responseData = [NSData dataWithData:self.dataAccumulator]; [_dataAccumulator release]; _dataAccumulator = nil; } From c2e5ca2726e5d32d483210302653bbf0d86717bd Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:47:51 -0500 Subject: [PATCH 09/65] Renaming _responseBody ivar to _responseData --- AFNetworking/AFURLConnectionOperation.h | 2 +- AFNetworking/AFURLConnectionOperation.m | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 9c7ba9a..8c620aa 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -49,7 +49,7 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; NSHTTPURLResponse *_response; NSError *_error; - NSData *_responseBody; + NSData *_responseData; NSInteger _totalBytesRead; NSMutableData *_dataAccumulator; NSOutputStream *_outputStream; diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8540ad1..9f89eda 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -78,7 +78,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { @synthesize request = _request; @synthesize response = _response; @synthesize error = _error; -@synthesize responseData = _responseBody; +@synthesize responseData = _responseData; @synthesize responseString = _responseString; @synthesize totalBytesRead = _totalBytesRead; @synthesize dataAccumulator = _dataAccumulator; @@ -129,7 +129,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [_response release]; [_error release]; - [_responseBody release]; + [_responseData release]; [_responseString release]; [_dataAccumulator release]; [_outputStream release]; _outputStream = nil; From 94f08de1d522611f4f2c98dc4ab61d634ba08c30 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 12:52:28 -0500 Subject: [PATCH 10/65] Adding mime types for other UIImage-supported file-types --- AFNetworking/AFImageRequestOperation.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index a1062b4..fe39825 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -113,7 +113,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/bmp", @"image/x-xbitmap", nil]; + self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; return self; } From 2c478758a2c5cf0b3d5e9ba08762ca80c5f79ef5 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 14:14:52 -0500 Subject: [PATCH 11/65] Adding Property List request operation Refactoring implementation of AFHTTPRequestOperation and subclasses --- AFNetworking/AFHTTPRequestOperation.m | 1 + AFNetworking/AFImageRequestOperation.m | 23 ++-- AFNetworking/AFJSONRequestOperation.m | 37 +++--- AFNetworking/AFPropertyListRequestOperation.h | 46 +++++++ AFNetworking/AFPropertyListRequestOperation.m | 116 ++++++++++++++++++ .../project.pbxproj | 6 + 6 files changed, 191 insertions(+), 38 deletions(-) create mode 100644 AFNetworking/AFPropertyListRequestOperation.h create mode 100644 AFNetworking/AFPropertyListRequestOperation.m diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 5e8bd60..8646873 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -72,6 +72,7 @@ - (void)dealloc { [_acceptableStatusCodes release]; + [_HTTPError release]; [super dealloc]; } diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index fe39825..81e2fef 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -34,25 +34,11 @@ static dispatch_queue_t image_request_operation_processing_queue() { @interface AFImageRequestOperation () @property (readwrite, nonatomic, retain) UIImage *responseImage; - -+ (UIImage *)imageWithData:(NSData *)data error:(NSError **)error ; @end @implementation AFImageRequestOperation @synthesize responseImage = _responseImage; -+ (UIImage *)imageWithData:(NSData *)data error:(NSError **)__unused error { - UIImage *image = nil; - if ([[UIScreen mainScreen] scale] == 2.0) { - CGImageRef imageRef = [[UIImage imageWithData:data] CGImage]; - image = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; - } else { - image = [UIImage imageWithData:data]; - } - - return image; -} - + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success { @@ -84,7 +70,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { }); } } else { - UIImage *image = [[self class] imageWithData:operation.responseData error:nil]; + UIImage *image = operation.responseImage; if (imageProcessingBlock) { image = imageProcessingBlock(image); @@ -125,7 +111,12 @@ static dispatch_queue_t image_request_operation_processing_queue() { - (UIImage *)responseImage { if (!_responseImage && [self isFinished]) { - self.responseImage = [[self class] imageWithData:self.responseData error:nil]; + if ([[UIScreen mainScreen] scale] == 2.0) { + CGImageRef imageRef = [[UIImage imageWithData:self.responseData] CGImage]; + self.responseImage = [UIImage imageWithCGImage:imageRef scale:2.0 orientation:UIImageOrientationUp]; + } else { + self.responseImage = [UIImage imageWithData:self.responseData]; + } } return _responseImage; diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index a820212..b3a65e3 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -37,35 +37,17 @@ static dispatch_queue_t json_request_operation_processing_queue() { @interface AFJSONRequestOperation () @property (readwrite, nonatomic, retain) id responseJSON; @property (readwrite, nonatomic, retain) NSError *error; - -+ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error; @end @implementation AFJSONRequestOperation @synthesize responseJSON = _responseJSON; @synthesize error = _JSONError; -+ (id)JSONObjectWithData:(NSData *)data error:(NSError **)error { - id JSON = nil; - -#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 - if ([NSJSONSerialization class]) { - JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:error]; - } else { - JSON = [[JSONDecoder decoder] objectWithData:data error:error]; - } -#else - JSON = [[JSONDecoder decoder] objectWithData:data error:error]; -#endif - - return JSON; -} - + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - AFJSONRequestOperation *operation = [[[AFJSONRequestOperation alloc] initWithRequest:urlRequest] autorelease]; + AFJSONRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; operation.completionBlock = ^ { if ([operation isCancelled]) { return; @@ -80,13 +62,13 @@ static dispatch_queue_t json_request_operation_processing_queue() { } else { dispatch_async(json_request_operation_processing_queue(), ^(void) { NSError *error = nil; - id JSON = [self JSONObjectWithData:operation.responseData error:&error]; + id JSON = operation.responseJSON; operation.error = error; dispatch_async(dispatch_get_main_queue(), ^(void) { if (operation.error) { if (failure) { - failure(operation.request, operation.response, error); + failure(operation.request, operation.response, operation.error); } } else { if (success) { @@ -114,13 +96,24 @@ static dispatch_queue_t json_request_operation_processing_queue() { - (void)dealloc { [_responseJSON release]; + [_JSONError release]; [super dealloc]; } - (id)responseJSON { if (!_responseJSON && [self isFinished]) { NSError *error = nil; - self.responseJSON = [[self class] JSONObjectWithData:self.responseData error:nil]; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 + if ([NSJSONSerialization class]) { + self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error]; + } else { + self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error]; + } +#else + self.responseJSON = [[JSONDecoder decoder] objectWithData:self.responseData error:&error]; +#endif + self.error = error; } diff --git a/AFNetworking/AFPropertyListRequestOperation.h b/AFNetworking/AFPropertyListRequestOperation.h new file mode 100644 index 0000000..9c2db3e --- /dev/null +++ b/AFNetworking/AFPropertyListRequestOperation.h @@ -0,0 +1,46 @@ +// AFPropertyListRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFHTTPRequestOperation.h" + +@interface AFPropertyListRequestOperation : AFHTTPRequestOperation { +@private + id _responsePropertyList; + NSPropertyListFormat _propertyListFormat; + NSPropertyListReadOptions _propertyListReadOptions; + NSError *_propertyListError; +} + +@property (readonly, nonatomic, retain) id responsePropertyList; +@property (readonly, nonatomic, assign) NSPropertyListFormat propertyListFormat; + +@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions; + +/** + + */ ++ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +@end diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m new file mode 100644 index 0000000..9d3847f --- /dev/null +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -0,0 +1,116 @@ +// AFPropertyListRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFPropertyListRequestOperation.h" + +static dispatch_queue_t af_property_list_request_operation_processing_queue; +static dispatch_queue_t property_list_request_operation_processing_queue() { + if (af_property_list_request_operation_processing_queue == NULL) { + af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0); + } + + return af_property_list_request_operation_processing_queue; +} + +@interface AFPropertyListRequestOperation () +@property (readwrite, nonatomic, retain) id responsePropertyList; +@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; +@property (readwrite, nonatomic, retain) NSError *error; +@end + +@implementation AFPropertyListRequestOperation +@synthesize responsePropertyList = _responsePropertyList; +@synthesize propertyListReadOptions = _propertyListReadOptions; +@synthesize propertyListFormat = _propertyListFormat; +@synthesize error = _propertyListError; + ++ (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + AFPropertyListRequestOperation *operation = [[[self alloc] initWithRequest:request] autorelease]; + operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + + if (operation.error) { + if (failure) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.request, operation.response, operation.error); + }); + } + } else { + dispatch_async(property_list_request_operation_processing_queue(), ^(void) { + id propertyList = operation.responsePropertyList; + + dispatch_async(dispatch_get_main_queue(), ^(void) { + if (operation.error) { + if (failure) { + failure(operation.request, operation.response, operation.error); + } + } else { + if (success) { + success(operation.request, operation.response, propertyList); + } + } + }); + }); + } + }; + + return operation; +} + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; + + self.propertyListReadOptions = NSPropertyListImmutable; + self.propertyListFormat = NSPropertyListXMLFormat_v1_0; + + return self; +} + +- (void)dealloc { + [_responsePropertyList release]; + [_propertyListError release]; + [super dealloc]; +} + +- (id)responsePropertyList { + if (!_responsePropertyList && [self isFinished]) { + NSPropertyListFormat format; + NSError *error = nil; + self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; + self.propertyListFormat = format; + self.error = error; + } + + return _responsePropertyList; +} + +@end diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 198fb15..8b1bd1c 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -30,6 +30,7 @@ F8E469671395739D00DB05C8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469661395739D00DB05C8 /* Foundation.framework */; }; F8E469691395739D00DB05C8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469681395739D00DB05C8 /* CoreGraphics.framework */; }; F8E469DF13957DD500DB05C8 /* CoreLocation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8E469DE13957DD500DB05C8 /* CoreLocation.framework */; }; + F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */; }; F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8FBFA97142AA238001409DB /* AFHTTPClient.m */; }; /* End PBXBuildFile section */ @@ -74,6 +75,8 @@ F8E469DE13957DD500DB05C8 /* CoreLocation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreLocation.framework; path = System/Library/Frameworks/CoreLocation.framework; sourceTree = SDKROOT; }; F8E469E013957DF100DB05C8 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; F8E469E213957DF700DB05C8 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFPropertyListRequestOperation.h; path = ../AFNetworking/AFPropertyListRequestOperation.h; sourceTree = ""; }; + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = ""; }; F8FBFA96142AA237001409DB /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = ""; }; F8FBFA97142AA238001409DB /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = ""; }; /* End PBXFileReference section */ @@ -234,6 +237,8 @@ F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F874B5D213E0AA6500B28E3E /* AFImageCache.h */, F874B5CA13E0AA6500B28E3E /* AFImageCache.m */, F874B5D513E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.h */, @@ -341,6 +346,7 @@ F874B5E013E0AA6500B28E3E /* UIImageView+AFNetworking.m in Sources */, F8FBFA98142AA239001409DB /* AFHTTPClient.m in Sources */, F86E5529143A28F3002B438C /* AFURLConnectionOperation.m in Sources */, + F8F4B16E143CD1420064C9E6 /* AFPropertyListRequestOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From c2be31d4fa9acca15f21a91ca2804e7164b33f77 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 5 Oct 2011 15:44:51 -0500 Subject: [PATCH 12/65] First implementation of protocol for AFHTTPClient to register classes to automatically determine the appropriate operation to create Wrapping AFURLConnectionOperation -setCompletionBlock: with blockSelf release pattern to avoid retain cycle --- AFNetworking/AFHTTPClient.h | 7 ++ AFNetworking/AFHTTPClient.m | 39 ++++++++--- AFNetworking/AFHTTPRequestOperation.h | 15 +++-- AFNetworking/AFHTTPRequestOperation.m | 66 +++++++++++-------- AFNetworking/AFImageRequestOperation.m | 23 +++++++ AFNetworking/AFJSONRequestOperation.m | 22 +++++++ AFNetworking/AFPropertyListRequestOperation.m | 22 +++++++ AFNetworking/AFURLConnectionOperation.m | 14 +++- AFNetworking/UIImageView+AFNetworking.m | 2 +- .../project.pbxproj | 4 +- Example/Classes/AFGowallaAPIClient.m | 4 ++ Example/Classes/Views/SpotTableViewCell.m | 21 ++++++ 12 files changed, 191 insertions(+), 48 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index c095d28..5eb0f02 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -49,6 +49,7 @@ @private NSURL *_baseURL; NSStringEncoding _stringEncoding; + NSMutableArray *_registeredHTTPOperationClassNames; NSMutableDictionary *_defaultHeaders; NSOperationQueue *_operationQueue; } @@ -96,6 +97,12 @@ */ - (id)initWithBaseURL:(NSURL *)url; +///---------------------------------- +/// @name Managing HTTP Operations +///---------------------------------- + +- (BOOL)registerHTTPOperationClass:(Class)operationClass; + ///---------------------------------- /// @name Managing HTTP Header Values ///---------------------------------- diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 05f989a..b936e95 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -77,6 +77,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @interface AFHTTPClient () @property (readwrite, nonatomic, retain) NSURL *baseURL; +@property (readwrite, nonatomic, retain) NSMutableArray *registeredHTTPOperationClassNames; @property (readwrite, nonatomic, retain) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, retain) NSOperationQueue *operationQueue; @end @@ -84,6 +85,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @implementation AFHTTPClient @synthesize baseURL = _baseURL; @synthesize stringEncoding = _stringEncoding; +@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; @synthesize defaultHeaders = _defaultHeaders; @synthesize operationQueue = _operationQueue; @@ -101,6 +103,8 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS self.stringEncoding = NSUTF8StringEncoding; + self.registeredHTTPOperationClassNames = [NSMutableArray array]; + self.defaultHeaders = [NSMutableDictionary dictionary]; // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 @@ -124,11 +128,28 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS - (void)dealloc { [_baseURL release]; + [_registeredHTTPOperationClassNames release]; [_defaultHeaders release]; [_operationQueue release]; [super dealloc]; } +#pragma mark - + +- (BOOL)registerHTTPOperationClass:(Class)operationClass { + if (![operationClass conformsToProtocol:@protocol(AFHTTPClientOperation)]) { + return NO; + } + + NSString *className = NSStringFromClass(operationClass); + [self.registeredHTTPOperationClassNames removeObject:className]; + [self.registeredHTTPOperationClassNames insertObject:className atIndex:0]; + + return YES; +} + +#pragma mark - + - (NSString *)defaultValueForHeader:(NSString *)header { return [self.defaultHeaders valueForKey:header]; } @@ -228,16 +249,16 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { - AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:urlRequest success:^(__unused NSURLRequest *request, __unused NSHTTPURLResponse *response, id JSON) { - if (success) { - success(JSON); + AFHTTPRequestOperation *operation = nil; + NSString *className = nil; + NSEnumerator *enumerator = [self.registeredHTTPOperationClassNames reverseObjectEnumerator]; + while (!operation && (className = [enumerator nextObject])) { + Class class = NSClassFromString(className); + if (class && [class canProcessRequest:urlRequest]) { + operation = [class HTTPRequestOperationWithRequest:urlRequest success:success failure:failure]; } - } failure:^(__unused NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { - if (failure) { - failure(response, error); - } - }]; - + } + [self.operationQueue addOperation:operation]; } diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 714c1a4..0ac8678 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -23,9 +23,12 @@ #import #import "AFURLConnectionOperation.h" -@protocol AFHTTPClientRequestOperation -+ (BOOL)canInitWithRequest:(NSURLRequest *)request; +@protocol AFHTTPClientOperation ++ (BOOL)canProcessRequest:(NSURLRequest *)request; + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; ++ (id)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; @end /** @@ -59,7 +62,7 @@ @see NSOperation @see NSURLConnection */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation { +@interface AFHTTPRequestOperation : AFURLConnectionOperation { @private NSIndexSet *_acceptableStatusCodes; NSSet *_acceptableContentTypes; @@ -80,9 +83,9 @@ /// @name Creating HTTP Request Operations ///--------------------------------------- -+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; +//+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest +// success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success +// failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; ///------------------------------- /// @name Validating HTTP Response diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 8646873..7ed0025 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -31,34 +31,6 @@ @synthesize acceptableContentTypes = _acceptableContentTypes; @synthesize error = _HTTPError; -+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure -{ - AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; - operation.completionBlock = ^ { - if ([operation isCancelled]) { - return; - } - - if (operation.error) { - if (failure) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - failure(operation.request, operation.response, operation.error); - }); - } - } else { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, operation.responseData); - }); - } - } - }; - - return operation; -} - - (id)initWithRequest:(NSURLRequest *)request { self = [super initWithRequest:request]; if (!self) { @@ -108,4 +80,42 @@ return !self.acceptableContentTypes || [self.acceptableContentTypes containsObject:[self.response MIMEType]]; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + return NO; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +{ + AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; + operation.completionBlock = ^ { + if ([operation isCancelled]) { + return; + } + + if (operation.error) { + if (failure) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + failure(operation.response, operation.error); + }); + } + } else { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^(void) { + success(operation.responseData); + }); + } + } + }; + + return operation; +} + @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 81e2fef..ba68b23 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -122,4 +122,27 @@ static dispatch_queue_t image_request_operation_processing_queue() { return _responseImage; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + NSSet *acceptablePathExtensions = [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [acceptablePathExtensions containsObject:[[request URL] pathExtension]]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +{ + return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { + success(image); + } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) { + failure(response, error); + }]; +} + @end diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index b3a65e3..c3373e3 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -120,4 +120,26 @@ static dispatch_queue_t json_request_operation_processing_queue() { return _responseJSON; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"json"]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +{ + return [self JSONRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id JSON) { + success(JSON); + } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) { + failure(response, error); + }]; +} + @end diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index 9d3847f..6fabbf5 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -113,4 +113,26 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { return _responsePropertyList; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; + return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"plist"]; +} + ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { + return request; +} + ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +{ + return [self propertyListRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, id propertyList) { + success(propertyList); + } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) { + failure(response, error); + }]; +} + @end diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 9f89eda..fcc7001 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -142,6 +142,18 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [super dealloc]; } +- (void)setCompletionBlock:(void (^)(void))block { + if (!block) { + [super setCompletionBlock:nil]; + } + + __block id _blockSelf = [self retain]; + [super setCompletionBlock:^ { + block(); + [_blockSelf autorelease]; + }]; +} + - (NSInputStream *)inputStream { return self.request.HTTPBodyStream; } @@ -194,8 +206,6 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { switch (state) { case AFHTTPOperationExecutingState: return YES; - case AFHTTPOperationFinishedState: - return [self isCancelled]; default: return NO; } diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index 6d0a10e..de894d5 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -78,7 +78,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response,UIImage *image))success + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:self.af_imageRequestOperation.request.URL])) { diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 8b1bd1c..a07cfe0 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -233,12 +233,12 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8FBFA96142AA237001409DB /* AFHTTPClient.h */, F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, F874B5CB13E0AA6500B28E3E /* AFImageRequestOperation.m */, - F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, - F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F874B5D213E0AA6500B28E3E /* AFImageCache.h */, F874B5CA13E0AA6500B28E3E /* AFImageCache.m */, F874B5D513E0AA6500B28E3E /* AFNetworkActivityIndicatorManager.h */, diff --git a/Example/Classes/AFGowallaAPIClient.m b/Example/Classes/AFGowallaAPIClient.m index 76ac24d..e83a320 100644 --- a/Example/Classes/AFGowallaAPIClient.m +++ b/Example/Classes/AFGowallaAPIClient.m @@ -22,6 +22,8 @@ #import "AFGowallaAPIClient.h" +#import "AFJSONRequestOperation.h" + // Replace this with your own API Key, available at http://api.gowalla.com/api/keys/ NSString * const kAFGowallaClientID = @"e7ccb7d3d2414eb2af4663fc91eb2793"; @@ -54,6 +56,8 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; // X-UDID HTTP Header [self setDefaultHeader:@"X-UDID" value:[[UIDevice currentDevice] uniqueIdentifier]]; + [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; + return self; } diff --git a/Example/Classes/Views/SpotTableViewCell.m b/Example/Classes/Views/SpotTableViewCell.m index c8feb4c..b576281 100644 --- a/Example/Classes/Views/SpotTableViewCell.m +++ b/Example/Classes/Views/SpotTableViewCell.m @@ -43,6 +43,7 @@ self.detailTextLabel.backgroundColor = self.backgroundColor; self.imageView.backgroundColor = self.backgroundColor; + self.imageView.contentMode = UIViewContentModeScaleAspectFit; self.selectionStyle = UITableViewCellSelectionStyleGray; @@ -73,4 +74,24 @@ self.detailTextLabel.text = nil; } +#pragma mark - UIView + +- (void)layoutSubviews { + [super layoutSubviews]; + CGRect imageViewFrame = self.imageView.frame; + CGRect textLabelFrame = self.textLabel.frame; + CGRect detailTextLabelFrame = self.detailTextLabel.frame; + + imageViewFrame.origin = CGPointMake(10.0f, 10.0f); + imageViewFrame.size = CGSizeMake(50.0f, 50.0f); + textLabelFrame.origin.x = imageViewFrame.size.width + 25.0f; + detailTextLabelFrame.origin.x = textLabelFrame.origin.x; + textLabelFrame.size.width = 240.0f; + detailTextLabelFrame.size.width = textLabelFrame.size.width; + + self.textLabel.frame = textLabelFrame; + self.detailTextLabel.frame = detailTextLabelFrame; + self.imageView.frame = imageViewFrame; +} + @end From 9b1c1f285cba569abb7626d2fc9e115e9b837331 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 10:15:58 -0500 Subject: [PATCH 13/65] Checking for cancellation early in -operationDidStart --- AFNetworking/AFURLConnectionOperation.m | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index fcc7001..353a12e 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -271,6 +271,11 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } - (void)operationDidStart { + if ([self isCancelled]) { + [self finish]; + return; + } + self.connection = [[[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO] autorelease]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; From c1dbf407be8ca0877c00a0ee95622605405dbfe9 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 10:43:48 -0500 Subject: [PATCH 14/65] [Issue #65] Adding slight delay when hiding network activity indicator, to avoid flickering --- .../AFNetworkActivityIndicatorManager.h | 1 + .../AFNetworkActivityIndicatorManager.m | 30 +++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.h b/AFNetworking/AFNetworkActivityIndicatorManager.h index 4cd8908..9df6098 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.h +++ b/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -29,6 +29,7 @@ @private NSInteger _activityCount; BOOL _enabled; + NSTimer *_activityIndicatorVisibilityTimer; } /** diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index 7094ea6..f24b7c0 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -24,13 +24,21 @@ #import "AFHTTPRequestOperation.h" +static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25; + @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, retain) NSTimer *activityIndicatorVisibilityTimer; +@property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateNetworkActivityIndicatorVisibility; @end @implementation AFNetworkActivityIndicatorManager @synthesize activityCount = _activityCount; +@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; @synthesize enabled = _enabled; +@dynamic networkActivityIndicatorVisible; + (AFNetworkActivityIndicatorManager *)sharedManager { static AFNetworkActivityIndicatorManager *_sharedManager = nil; @@ -50,13 +58,16 @@ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; - + return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; + [_activityIndicatorVisibilityTimer invalidate]; + [_activityIndicatorVisibilityTimer release]; _activityIndicatorVisibilityTimer = nil; + [super dealloc]; } @@ -66,10 +77,25 @@ [self didChangeValueForKey:@"activityCount"]; if (self.enabled) { - [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:self.activityCount > 0]; + // Delay hiding of activity indicator for a short interval, to avoid flickering + if (![self isNetworkActivityIndicatorVisible]) { + [self.activityIndicatorVisibilityTimer invalidate]; + self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; + } else { + [self updateNetworkActivityIndicatorVisibility]; + } } } +- (BOOL)isNetworkActivityIndicatorVisible { + return self.activityCount > 0; +} + +- (void)updateNetworkActivityIndicatorVisibility { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; +} + - (void)incrementActivityCount { @synchronized(self) { self.activityCount += 1; From 6f20f84ef15d10fe59c38770563158459f40416d Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Thu, 6 Oct 2011 14:33:16 -0500 Subject: [PATCH 15/65] Adding AFHTTPClientParameterEncoding @property to AFHTTPClient, which determines the method of encoding an NSDictionary of parameters for the body of an HTTP request Minor refactoring of AFRestClient --- AFNetworking/AFHTTPClient.h | 15 +++ AFNetworking/AFHTTPClient.m | 102 ++++++++++++++---- .../project.pbxproj | 4 +- 3 files changed, 98 insertions(+), 23 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 5eb0f02..2e31c27 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -25,6 +25,12 @@ @protocol AFMultipartFormData; +typedef enum { + AFFormURLParameterEncoding, + AFJSONParameterEncoding, + AFPropertyListParameterEncoding, +} AFHTTPClientParameterEncoding; + /** `AFHTTPClient` objects encapsulates the common patterns of communicating with an application, webservice, or API. It encapsulates persistent information, like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations. @@ -49,6 +55,7 @@ @private NSURL *_baseURL; NSStringEncoding _stringEncoding; + AFHTTPClientParameterEncoding _parameterEncoding; NSMutableArray *_registeredHTTPOperationClassNames; NSMutableDictionary *_defaultHeaders; NSOperationQueue *_operationQueue; @@ -68,6 +75,11 @@ */ @property (nonatomic, assign) NSStringEncoding stringEncoding; +/** + + */ +@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding; + /** The operation queue which manages operations enqueued by the HTTP client. */ @@ -193,6 +205,9 @@ - (void)enqueueHTTPRequestOperationWithRequest:(NSURLRequest *)request success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; +/** + */ +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation; ///--------------------------------- /// @name Cancelling HTTP Operations diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index b936e95..ce9a9ad 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -22,6 +22,9 @@ #import "AFHTTPClient.h" #import "AFJSONRequestOperation.h" +#import "JSONKit.h" + +#include static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; @@ -40,6 +43,8 @@ static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY" #pragma mark - +static NSUInteger const kAFHTTPClientDefaultMaxConcurrentOperationCount = 4; + static NSString * AFBase64EncodedStringFromString(NSString *string) { NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string length]]; NSUInteger length = [data length]; @@ -69,10 +74,52 @@ static NSString * AFBase64EncodedStringFromString(NSString *string) { return [[[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding] autorelease]; } -static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { +static NSString * AFURLEncodedStringFromString(NSString *string) { static NSString * const kAFLegalCharactersToBeEscaped = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\|~ "; - return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease]; + return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) autorelease]; +} + +static NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutableParameterComponents = [NSMutableArray array]; + for (id key in [parameters allKeys]) { + NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromString([key description]), AFURLEncodedStringFromString([[parameters valueForKey:key] description])]; + [mutableParameterComponents addObject:component]; + } + + return [mutableParameterComponents componentsJoinedByString:@"&"]; +} + +static NSString * AFJSONStringFromParameters(NSDictionary *parameters) { + NSString *JSONString = nil; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 + if ([NSJSONSerialization class]) { + NSError *error = nil; + NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]; + if (!error) { + JSONString = [[[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding] autorelease]; + } + } else { + JSONString = [parameters JSONString]; + } +#else + JSONString = [parameters JSONString]; +#endif + + return JSONString; +} + +static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { + NSString *propertyListString = nil; + NSError *error = nil; + + NSData *propertyListData = [NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]; + if (!error) { + propertyListString = [[[NSString alloc] initWithData:propertyListData encoding:NSUTF8StringEncoding] autorelease]; + } + + return propertyListString; } @interface AFHTTPClient () @@ -85,6 +132,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS @implementation AFHTTPClient @synthesize baseURL = _baseURL; @synthesize stringEncoding = _stringEncoding; +@synthesize parameterEncoding = _parameterEncoding; @synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; @synthesize defaultHeaders = _defaultHeaders; @synthesize operationQueue = _operationQueue; @@ -102,6 +150,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS self.baseURL = url; self.stringEncoding = NSUTF8StringEncoding; + self.parameterEncoding = AFJSONParameterEncoding; self.registeredHTTPOperationClassNames = [NSMutableArray array]; @@ -121,7 +170,7 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS [self setDefaultHeader:@"User-Agent" value:[NSString stringWithFormat:@"%@/%@ (%@, %@ %@, %@, Scale/%f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey], @"unknown", [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] model], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0)]]; self.operationQueue = [[[NSOperationQueue alloc] init] autorelease]; - [self.operationQueue setMaxConcurrentOperationCount:2]; + [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount]; return self; } @@ -177,31 +226,34 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS path:(NSString *)path parameters:(NSDictionary *)parameters { - NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; - NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; + [request setHTTPMethod:method]; + [request setAllHTTPHeaderFields:self.defaultHeaders]; - if (parameters) { - NSMutableArray *mutableParameterComponents = [NSMutableArray array]; - for (id key in [parameters allKeys]) { - NSString *component = [NSString stringWithFormat:@"%@=%@", AFURLEncodedStringFromStringWithEncoding([key description], self.stringEncoding), AFURLEncodedStringFromStringWithEncoding([[parameters valueForKey:key] description], self.stringEncoding)]; - [mutableParameterComponents addObject:component]; - } - NSString *queryString = [mutableParameterComponents componentsJoinedByString:@"&"]; - + if (parameters) { if ([method isEqualToString:@"GET"]) { - url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", queryString]]; + url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParameters(parameters)]]; + [request setURL:url]; } else { NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); - [headers setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forKey:@"Content-Type"]; - [request setHTTPBody:[queryString dataUsingEncoding:self.stringEncoding]]; + switch (self.parameterEncoding) { + case AFFormURLParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[AFQueryStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]]; + break; + case AFJSONParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[AFJSONStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]]; + break; + case AFPropertyListParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[AFPropertyListStringFromParameters(parameters) dataUsingEncoding:self.stringEncoding]]; + break; + } } } - [request setURL:url]; - [request setHTTPMethod:method]; - [request setAllHTTPHeaderFields:headers]; - return request; } @@ -258,7 +310,15 @@ static NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSS operation = [class HTTPRequestOperationWithRequest:urlRequest success:success failure:failure]; } } + + if (!operation) { + operation = [AFHTTPRequestOperation HTTPRequestOperationWithRequest:urlRequest success:success failure:failure]; + } + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation { [self.operationQueue addOperation:operation]; } diff --git a/Example/AFNetworking Example.xcodeproj/project.pbxproj b/Example/AFNetworking Example.xcodeproj/project.pbxproj index 09644af..53eb182 100644 --- a/Example/AFNetworking Example.xcodeproj/project.pbxproj +++ b/Example/AFNetworking Example.xcodeproj/project.pbxproj @@ -236,10 +236,10 @@ F874B5C913E0AA6500B28E3E /* AFHTTPRequestOperation.m */, F874B5D413E0AA6500B28E3E /* AFJSONRequestOperation.h */, F874B5CC13E0AA6500B28E3E /* AFJSONRequestOperation.m */, - F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, - F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8F4B17D143E07030064C9E6 /* AFXMLRequestOperation.h */, F8F4B17E143E07030064C9E6 /* AFXMLRequestOperation.m */, + F8F4B16C143CD1410064C9E6 /* AFPropertyListRequestOperation.h */, + F8F4B16D143CD1410064C9E6 /* AFPropertyListRequestOperation.m */, F8FBFA96142AA237001409DB /* AFHTTPClient.h */, F8FBFA97142AA238001409DB /* AFHTTPClient.m */, F874B5D313E0AA6500B28E3E /* AFImageRequestOperation.h */, From 62596c25b9a8ecbf5f8c828ce12b806fb41d7deb Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 09:40:11 -0500 Subject: [PATCH 16/65] [Issue #72] Fixing HTTP Client method of constructing URLs from a path with respect to a base url --- AFNetworking/AFHTTPClient.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index ce9a9ad..94a99e8 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -226,7 +226,7 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { path:(NSString *)path parameters:(NSDictionary *)parameters { - NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSURL *url = [self.baseURL URLByAppendingPathComponent:path]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; [request setHTTPMethod:method]; [request setAllHTTPHeaderFields:self.defaultHeaders]; From 120247718d35a4329be60482b8a434abce991b21 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 09:40:32 -0500 Subject: [PATCH 17/65] Removing delegate argument to class method constructor --- AFNetworking/AFXMLRequestOperation.h | 1 - AFNetworking/AFXMLRequestOperation.m | 2 -- 2 files changed, 3 deletions(-) diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index a81e740..390153e 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -31,7 +31,6 @@ @property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser; + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - delegate:(id )delegate success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index f7a105c..00dd1fb 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -32,7 +32,6 @@ @synthesize responseXMLParser = _responseXMLParser; + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - delegate:(id )delegate success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { @@ -50,7 +49,6 @@ } } else { NSXMLParser *XMLParser = operation.responseXMLParser; - XMLParser.delegate = delegate; if (success) { success(operation.request, operation.response, XMLParser); } From 263e2f3d5c06c88fd88d60222e96c634c45d8dcc Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:04:57 -0500 Subject: [PATCH 18/65] [Issue #59] Removing unnecessary dispatch in UIImageView category --- AFNetworking/UIImageView+AFNetworking.m | 30 +++++++++++-------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index de894d5..ba880c4 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -81,7 +81,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure { - if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:self.af_imageRequestOperation.request.URL])) { + if (![urlRequest URL] || (![self.af_imageRequestOperation isCancelled] && [[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]])) { return; } else { [self cancelImageRequestOperation]; @@ -99,26 +99,22 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) { - dispatch_async(dispatch_get_main_queue(), ^{ - if (success) { - success(request, response, image); - } - - if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { - self.image = image; - } else { - self.image = placeholderImage; - } - }); + if (success) { + success(request, response, image); + } + + if ([[request URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { + self.image = image; + } else { + self.image = placeholderImage; + } } } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { self.af_imageRequestOperation = nil; - dispatch_async(dispatch_get_main_queue(), ^{ - if (failure) { - failure(request, response, error); - } - }); + if (failure) { + failure(request, response, error); + } }]; [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; From b7564e9f5aa6b14bec0861bb7720b93d0b650353 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:41:29 -0500 Subject: [PATCH 19/65] Refactoring implementation of AFHTTPRequest subclasses to fulfill AFHTTPClientOperation protocol --- AFNetworking/AFHTTPRequestOperation.m | 23 +------------- AFNetworking/AFImageRequestOperation.m | 21 ++++++++----- AFNetworking/AFJSONRequestOperation.m | 20 ++++++++----- AFNetworking/AFPropertyListRequestOperation.m | 18 +++++++---- AFNetworking/AFXMLRequestOperation.m | 30 ++++++++++++++++++- 5 files changed, 68 insertions(+), 44 deletions(-) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 7ed0025..a842c95 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -94,28 +94,7 @@ success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { - AFHTTPRequestOperation *operation = [[[self alloc] initWithRequest:urlRequest] autorelease]; - operation.completionBlock = ^ { - if ([operation isCancelled]) { - return; - } - - if (operation.error) { - if (failure) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - failure(operation.response, operation.error); - }); - } - } else { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.responseData); - }); - } - } - }; - - return operation; + return nil; } @end diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index ba68b23..9e7e956 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -34,6 +34,9 @@ static dispatch_queue_t image_request_operation_processing_queue() { @interface AFImageRequestOperation () @property (readwrite, nonatomic, retain) UIImage *responseImage; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFImageRequestOperation @@ -93,13 +96,21 @@ static dispatch_queue_t image_request_operation_processing_queue() { return operation; } ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; +} + ++ (NSSet *)defaultAcceptablePathExtensions { + return [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; +} + - (id)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -125,13 +136,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon" @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; - NSSet *acceptablePathExtensions = [NSSet setWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [acceptablePathExtensions containsObject:[[request URL] pathExtension]]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index c3373e3..61a4cbf 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -37,6 +37,9 @@ static dispatch_queue_t json_request_operation_processing_queue() { @interface AFJSONRequestOperation () @property (readwrite, nonatomic, retain) id responseJSON; @property (readwrite, nonatomic, retain) NSError *error; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFJSONRequestOperation @@ -83,13 +86,21 @@ static dispatch_queue_t json_request_operation_processing_queue() { return operation; } ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; +} + ++ (NSSet *)defaultAcceptablePathExtensions { + return [NSSet setWithObjects:@"json", nil]; +} + - (id)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -123,12 +134,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-javascript", @"text/javascript", @"text/x-javascript", @"text/x-json", @"text/json", @"text/plain", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"json"]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index 6fabbf5..eb2f7c4 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -35,6 +35,9 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { @property (readwrite, nonatomic, retain) id responsePropertyList; @property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; @property (readwrite, nonatomic, retain) NSError *error; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFPropertyListRequestOperation @@ -81,6 +84,14 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { return operation; } ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; +} + ++ (NSSet *)defaultAcceptablePathExtensions { + return [NSSet setWithObjects:@"plist", nil]; +} + - (id)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { @@ -116,12 +127,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { - NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; - return [acceptableContentTypes containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[[request URL] pathExtension] isEqualToString:@"plist"]; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; } + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 00dd1fb..057b2e5 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -26,6 +26,9 @@ @interface AFXMLRequestOperation () @property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser; + ++ (NSSet *)defaultAcceptableContentTypes; ++ (NSSet *)defaultAcceptablePathExtensions; @end @implementation AFXMLRequestOperation @@ -58,13 +61,21 @@ return operation; } ++ (NSSet *)defaultAcceptableContentTypes { + return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; +} + ++ (NSSet *)defaultAcceptablePathExtensions { + return [NSSet setWithObjects:@"xml", nil]; +} + - (id)initWithRequest:(NSURLRequest *)urlRequest { self = [super initWithRequest:urlRequest]; if (!self) { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; return self; } @@ -82,4 +93,21 @@ return _responseXMLParser; } +#pragma mark - AFHTTPClientOperation + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + return [[self defaultAcceptableContentTypes] containsObject:[request valueForHTTPHeaderField:@"Accept"]] || [[self defaultAcceptablePathExtensions] containsObject:[[request URL] pathExtension]]; +} + ++ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure +{ + return [self XMLParserRequestOperationWithRequest:urlRequest success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSXMLParser *XMLParser) { + success(XMLParser); + } failure:^(NSURLRequest __unused *request, NSHTTPURLResponse *response, NSError *error) { + failure(response, error); + }]; +} + @end From b28b99dd16882bea93e6ef357e90f9a9fad2f70c Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 10:51:23 -0500 Subject: [PATCH 20/65] Moving AFHTTPClientOperation protocol to AFHTTPClient Refactoring #import statements --- AFNetworking/AFHTTPClient.h | 13 ++++++++++++- AFNetworking/AFHTTPRequestOperation.h | 9 +-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 2e31c27..b0d3c14 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -21,8 +21,9 @@ // THE SOFTWARE. #import -#import "AFHTTPRequestOperation.h" +@class AFHTTPRequestOperation; +@protocol AFHTTPClientOperation; @protocol AFMultipartFormData; typedef enum { @@ -288,6 +289,16 @@ typedef enum { #pragma mark - +@protocol AFHTTPClientOperation ++ (BOOL)canProcessRequest:(NSURLRequest *)request; ++ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; ++ (id)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(id object))success + failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; +@end + +#pragma mark - + /** The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`. */ diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 0ac8678..8e66e54 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -22,14 +22,7 @@ #import #import "AFURLConnectionOperation.h" - -@protocol AFHTTPClientOperation -+ (BOOL)canProcessRequest:(NSURLRequest *)request; -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; -+ (id)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(id object))success - failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; -@end +#import "AFHTTPClient.h" /** `AFHTTPRequestOperation` is an `NSOperation` subclass that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. From 998f7bb701cbe896ba271074105a61b6bfbadc9b Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 11:06:31 -0500 Subject: [PATCH 21/65] nil-ing out responseXMLParser delegate if AFXMLRequestOperation is cancelled --- AFNetworking/AFXMLRequestOperation.m | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 057b2e5..e958e1c 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -93,6 +93,14 @@ return _responseXMLParser; } +#pragma mark - NSOperation + +- (void)cancel { + [super cancel]; + + self.responseXMLParser.delegate = nil; +} + #pragma mark - AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request { From db3dddb03be167620bab001c3bd58e7f18aba046 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 11:07:14 -0500 Subject: [PATCH 22/65] Setting _responseXMLParser delegate to nil in AFXMLRequestOperation -dealloc --- AFNetworking/AFXMLRequestOperation.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index e958e1c..9f7b72c 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -81,7 +81,9 @@ } - (void)dealloc { + _responseXMLParser.delegate = nil; [_responseXMLParser release]; + [super dealloc]; } From ce9872965c85b490dcba3eb3f504b6dc312dc87f Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:05:22 -0500 Subject: [PATCH 23/65] [Issue #56] Fixing 'The Dealloc Problem' --- AFNetworking/AFURLConnectionOperation.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 353a12e..8015bd6 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -147,10 +147,10 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { [super setCompletionBlock:nil]; } - __block id _blockSelf = [self retain]; + __block id _blockSelf = self; [super setCompletionBlock:^ { block(); - [_blockSelf autorelease]; + [_blockSelf setCompletionBlock:nil]; }]; } From 3e27e189ee16615619b9da2b92175acb5a1535ec Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:05:47 -0500 Subject: [PATCH 24/65] Adding missing release for _acceptableContentTypes in AFHTTPRequestOperation -dealloc --- AFNetworking/AFHTTPRequestOperation.m | 1 + 1 file changed, 1 insertion(+) diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index a842c95..6f052d5 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -44,6 +44,7 @@ - (void)dealloc { [_acceptableStatusCodes release]; + [_acceptableContentTypes release]; [_HTTPError release]; [super dealloc]; } From b7724922c45706463d1208c8ae42b8c403777d92 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:06:12 -0500 Subject: [PATCH 25/65] Refactoring image request operation --- AFNetworking/AFImageRequestOperation.m | 3 +-- AFNetworking/UIImageView+AFNetworking.m | 10 +++++----- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 9e7e956..9e2ba89 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -81,7 +81,6 @@ static dispatch_queue_t image_request_operation_processing_queue() { if (success) { dispatch_async(dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, image); }); } @@ -90,7 +89,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { [[AFImageCache sharedImageCache] cacheImage:image forURL:[operation.request URL] cacheName:cacheNameOrNil]; } } - }); + }); }; return operation; diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index ba880c4..74f718b 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -27,7 +27,7 @@ #import "AFImageCache.h" -static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOperation"; +static char kAFImageRequestOperationObjectKey; @interface UIImageView (_AFNetworking) @property (readwrite, nonatomic, retain, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; @@ -42,11 +42,11 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp @implementation UIImageView (AFNetworking) - (AFHTTPRequestOperation *)af_imageRequestOperation { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, kAFImageRequestOperationObjectKey); + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); } - (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { - objc_setAssociatedObject(self, kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } + (NSOperationQueue *)af_sharedImageRequestOperationQueue { @@ -97,7 +97,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { self.image = placeholderImage; - self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { + self.af_imageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil cacheName:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { if (self.af_imageRequestOperation && ![self.af_imageRequestOperation isCancelled]) { if (success) { success(request, response, image); @@ -108,7 +108,7 @@ static NSString * const kAFImageRequestOperationObjectKey = @"_af_imageRequestOp } else { self.image = placeholderImage; } - } + } } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { self.af_imageRequestOperation = nil; From f1fa6f1a6f664e9fdbceb728b9dccdf04505631a Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:18:41 -0500 Subject: [PATCH 26/65] [Issue #56] Wrapping completion block in async_dispatch to main queue --- AFNetworking/AFURLConnectionOperation.m | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 8015bd6..be7e10f 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -149,8 +149,10 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { __block id _blockSelf = self; [super setCompletionBlock:^ { - block(); - [_blockSelf setCompletionBlock:nil]; + dispatch_async(dispatch_get_main_queue(), ^(void) { + block(); + [_blockSelf setCompletionBlock:nil]; + }); }]; } From 95bcd2278c0bdbf6847a7c9939beece2b32091a2 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Mon, 10 Oct 2011 13:26:17 -0500 Subject: [PATCH 27/65] Only execute in main queue --- AFNetworking/AFURLConnectionOperation.m | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index be7e10f..30e04e8 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -149,8 +149,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { __block id _blockSelf = self; [super setCompletionBlock:^ { + block(); + dispatch_async(dispatch_get_main_queue(), ^(void) { - block(); [_blockSelf setCompletionBlock:nil]; }); }]; From 191b37803863fda069624d3592533a0279a1abff Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:00:09 -0500 Subject: [PATCH 28/65] Adding missing macros for iOS conditional compilation of activity indicator manager --- AFNetworking/AFNetworkActivityIndicatorManager.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index efd8d34..eb0c8e8 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -24,6 +24,7 @@ #import "AFHTTPRequestOperation.h" +#if __IPHONE_OS_VERSION_MIN_REQUIRED @interface AFNetworkActivityIndicatorManager () @property (readwrite, nonatomic, assign) NSInteger activityCount; @end @@ -83,3 +84,4 @@ } @end +#endif \ No newline at end of file From 7e4b22415479c038fb1c9e9afc80b5c7f8bdb483 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:05:07 -0500 Subject: [PATCH 29/65] Cleaning up merge with experimental-0.7 --- AFNetworking/AFImageRequestOperation.h | 5 +++- AFNetworking/AFImageRequestOperation.m | 2 ++ .../AFNetworkActivityIndicatorManager.m | 2 ++ .../project.pbxproj | 28 +++++++++++++++---- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index b7ee9bb..42e5859 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -21,9 +21,11 @@ // THE SOFTWARE. #import -#import #import "AFHTTPRequestOperation.h" +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import + /** `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. @@ -66,3 +68,4 @@ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; @end +#endif diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 9e2ba89..44e9309 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -32,6 +32,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { return af_image_request_operation_processing_queue; } +#if __IPHONE_OS_VERSION_MIN_REQUIRED @interface AFImageRequestOperation () @property (readwrite, nonatomic, retain) UIImage *responseImage; @@ -150,3 +151,4 @@ static dispatch_queue_t image_request_operation_processing_queue() { } @end +#endif diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.m b/AFNetworking/AFNetworkActivityIndicatorManager.m index f24b7c0..88f7e46 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.m +++ b/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -24,6 +24,7 @@ #import "AFHTTPRequestOperation.h" +#if __IPHONE_OS_VERSION_MIN_REQUIRED static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25; @interface AFNetworkActivityIndicatorManager () @@ -109,3 +110,4 @@ static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.25; } @end +#endif diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index d320e92..cff18be 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -7,6 +7,9 @@ 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"; }; }; 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"; }; }; @@ -24,6 +27,12 @@ /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + F87A159D1444926300318955 /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLConnectionOperation.h; sourceTree = ""; }; + F87A159E1444926300318955 /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLConnectionOperation.m; sourceTree = ""; }; + F87A15A01444926900318955 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFXMLRequestOperation.h; sourceTree = ""; }; + F87A15A11444926900318955 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = ""; }; + F87A15A31444927300318955 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFPropertyListRequestOperation.h; sourceTree = ""; }; + F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListRequestOperation.m; sourceTree = ""; }; F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPClient.h; sourceTree = ""; }; F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClient.m; sourceTree = ""; }; F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperation.h; sourceTree = ""; }; @@ -70,19 +79,25 @@ F897DE68142CFEDC000DDD35 /* AFNetworking */ = { isa = PBXGroup; children = ( - F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */, - F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */, + 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 */, F897DE6D142CFEDC000DDD35 /* AFImageCache.h */, F897DE6E142CFEDC000DDD35 /* AFImageCache.m */, F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */, F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */, - F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */, - F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */, F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */, F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */, - F897DE75142CFEDC000DDD35 /* AFNetworking.h */, F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */, F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */, ); @@ -265,6 +280,9 @@ F897DE7C142CFEDC000DDD35 /* AFJSONRequestOperation.m in Sources */, F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */, F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */, + F87A159F1444926300318955 /* AFURLConnectionOperation.m in Sources */, + F87A15A21444926A00318955 /* AFXMLRequestOperation.m in Sources */, + F87A15A51444927300318955 /* AFPropertyListRequestOperation.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From 70351a51e11116d3e321f227a0f1f83645673215 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:20:01 -0500 Subject: [PATCH 30/65] Adding 0.7 classes to main header --- AFNetworking/AFNetworking.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFNetworking.h b/AFNetworking/AFNetworking.h index 0f010a6..3deeec6 100644 --- a/AFNetworking/AFNetworking.h +++ b/AFNetworking/AFNetworking.h @@ -25,6 +25,8 @@ #import #import +#import +#import #import #import From 4c7816e716cdfe1f99309fca72000e34c3b72c44 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:20:22 -0500 Subject: [PATCH 31/65] Adding conditional NSXMLDocument support for Mac platform --- AFNetworking/AFXMLRequestOperation.h | 17 +++++++++++++++++ AFNetworking/AFXMLRequestOperation.m | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index 390153e..450c601 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -23,15 +23,32 @@ #import #import "AFHTTPRequestOperation.h" +#import + @interface AFXMLRequestOperation : AFHTTPRequestOperation { @private NSXMLParser *_responseXMLParser; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + NSXMLDocument *_responseXMLDocument; +#endif + NSError *_XMLError; } @property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +@property (readonly, nonatomic, retain) NSXMLDocument *responseXMLDocument; +#endif + + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +#ifdef __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; +#endif + @end diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 9f7b72c..579d9bb 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -26,6 +26,10 @@ @interface AFXMLRequestOperation () @property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +@property (readwrite, nonatomic, retain) NSXMLDocument *responseXMLDocument; +#endif +@property (readwrite, nonatomic, retain) NSError *error; + (NSSet *)defaultAcceptableContentTypes; + (NSSet *)defaultAcceptablePathExtensions; @@ -33,6 +37,10 @@ @implementation AFXMLRequestOperation @synthesize responseXMLParser = _responseXMLParser; +#ifdef __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 @@ -84,6 +92,12 @@ _responseXMLParser.delegate = nil; [_responseXMLParser release]; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + [_responseXMLDocument release]; +#endif + + [_XMLError release]; + [super dealloc]; } @@ -95,6 +109,18 @@ return _responseXMLParser; } +#ifdef __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 { From 72090fd4e2ac646294dc153c93806217bbe03043 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:22:40 -0500 Subject: [PATCH 32/65] Adding native JSON serialization macro check for Mac --- AFNetworking/AFJSONRequestOperation.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index 61a4cbf..a8f548c 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -115,7 +115,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { if (!_responseJSON && [self isFinished]) { NSError *error = nil; -#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 +#if __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6 || __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 if ([NSJSONSerialization class]) { self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error]; } else { From 53d61e7eb28966b05210915140815f21f5c0b389 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:39:41 -0500 Subject: [PATCH 33/65] Adding pre-processor directives to conditionally compile Mac equivalent of UIKit-dependent APIs --- AFNetworking/AFHTTPClient.h | 1 - AFNetworking/AFHTTPRequestOperation.m | 4 -- AFNetworking/AFImageCache.h | 7 ++ AFNetworking/AFImageCache.m | 19 ++++- AFNetworking/AFImageRequestOperation.h | 27 ++++++- AFNetworking/AFImageRequestOperation.m | 95 +++++++++++++++++++++++-- AFNetworking/AFJSONRequestOperation.m | 2 +- AFNetworking/AFXMLRequestOperation.h | 6 +- AFNetworking/AFXMLRequestOperation.m | 46 +++++++++++- AFNetworking/UIImageView+AFNetworking.h | 4 +- 10 files changed, 191 insertions(+), 20 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index b0d3c14..1847fc5 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -291,7 +291,6 @@ typedef enum { @protocol AFHTTPClientOperation + (BOOL)canProcessRequest:(NSURLRequest *)request; -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request; + (id)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure; diff --git a/AFNetworking/AFHTTPRequestOperation.m b/AFNetworking/AFHTTPRequestOperation.m index 6f052d5..69bc370 100644 --- a/AFNetworking/AFHTTPRequestOperation.m +++ b/AFNetworking/AFHTTPRequestOperation.m @@ -87,10 +87,6 @@ return NO; } -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { - return request; -} - + (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(id object))success failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure diff --git a/AFNetworking/AFImageCache.h b/AFNetworking/AFImageCache.h index 66c0044..8c16508 100644 --- a/AFNetworking/AFImageCache.h +++ b/AFNetworking/AFImageCache.h @@ -51,6 +51,9 @@ #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 /** @@ -65,6 +68,10 @@ - (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 diff --git a/AFNetworking/AFImageCache.m b/AFNetworking/AFImageCache.m index b62e5bc..ad7a2b1 100644 --- a/AFNetworking/AFImageCache.m +++ b/AFNetworking/AFImageCache.m @@ -45,6 +45,12 @@ static inline NSString * AFImageCacheKeyFromURLAndCacheName(NSURL *url, NSString { 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 @@ -55,7 +61,18 @@ static inline NSString * AFImageCacheKeyFromURLAndCacheName(NSURL *url, NSString if (!image) { return; } - + + [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 diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 42e5859..06e130d 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -23,8 +23,13 @@ #import #import "AFHTTPRequestOperation.h" +#import + #if __IPHONE_OS_VERSION_MIN_REQUIRED #import +#elif __MAC_OS_X_VERSION_MIN_REQUIRED +#import +#endif /** `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. @@ -34,10 +39,18 @@ */ @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. @@ -47,8 +60,13 @@ @return A new image request operation */ +#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. @@ -61,11 +79,18 @@ @return A new image request operation */ +#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 -#endif diff --git a/AFNetworking/AFImageRequestOperation.m b/AFNetworking/AFImageRequestOperation.m index 44e9309..c31cd3d 100644 --- a/AFNetworking/AFImageRequestOperation.m +++ b/AFNetworking/AFImageRequestOperation.m @@ -32,9 +32,12 @@ static dispatch_queue_t image_request_operation_processing_queue() { return af_image_request_operation_processing_queue; } -#if __IPHONE_OS_VERSION_MIN_REQUIRED @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 + (NSSet *)defaultAcceptableContentTypes; + (NSSet *)defaultAcceptablePathExtensions; @@ -43,6 +46,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { @implementation AFImageRequestOperation @synthesize responseImage = _responseImage; +#if __IPHONE_OS_VERSION_MIN_REQUIRED + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(UIImage *image))success { @@ -52,12 +56,25 @@ static dispatch_queue_t image_request_operation_processing_queue() { } } failure:nil]; } +#elif __MAC_OS_X_VERSION_MIN_REQUIRED ++ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSImage *image))success +{ + 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 + 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]; @@ -95,6 +112,50 @@ static dispatch_queue_t image_request_operation_processing_queue() { 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]; @@ -120,6 +181,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { [super dealloc]; } +#if __IPHONE_OS_VERSION_MIN_REQUIRED - (UIImage *)responseImage { if (!_responseImage && [self isFinished]) { if ([[UIScreen mainScreen] scale] == 2.0) { @@ -132,6 +194,15 @@ static dispatch_queue_t image_request_operation_processing_queue() { 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 @@ -139,6 +210,7 @@ static dispatch_queue_t image_request_operation_processing_queue() { 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 @@ -149,6 +221,17 @@ static dispatch_queue_t image_request_operation_processing_queue() { 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 -#endif diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index a8f548c..a268cfa 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -115,7 +115,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { if (!_responseJSON && [self isFinished]) { NSError *error = nil; -#if __MAC_OS_X_VERSION_MIN_REQUIRED > __MAC_10_6 || __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 +#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 { diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index 450c601..2bbde74 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -28,7 +28,7 @@ @interface AFXMLRequestOperation : AFHTTPRequestOperation { @private NSXMLParser *_responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED NSXMLDocument *_responseXMLDocument; #endif NSError *_XMLError; @@ -36,7 +36,7 @@ @property (readonly, nonatomic, retain) NSXMLParser *responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED @property (readonly, nonatomic, retain) NSXMLDocument *responseXMLDocument; #endif @@ -45,7 +45,7 @@ failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#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; diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index 579d9bb..d57374a 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -24,9 +24,18 @@ #include +static dispatch_queue_t af_xml_request_operation_processing_queue; +static dispatch_queue_t xml_request_operation_processing_queue() { + if (af_xml_request_operation_processing_queue == NULL) { + af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0); + } + + return af_xml_request_operation_processing_queue; +} + @interface AFXMLRequestOperation () @property (readwrite, nonatomic, retain) NSXMLParser *responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED @property (readwrite, nonatomic, retain) NSXMLDocument *responseXMLDocument; #endif @property (readwrite, nonatomic, retain) NSError *error; @@ -37,7 +46,7 @@ @implementation AFXMLRequestOperation @synthesize responseXMLParser = _responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED @synthesize responseXMLDocument = _responseXMLDocument; #endif @synthesize error = _XMLError; @@ -69,6 +78,39 @@ 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]; } diff --git a/AFNetworking/UIImageView+AFNetworking.h b/AFNetworking/UIImageView+AFNetworking.h index d28514b..71ecdc0 100644 --- a/AFNetworking/UIImageView+AFNetworking.h +++ b/AFNetworking/UIImageView+AFNetworking.h @@ -20,11 +20,13 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +#import +#import "AFImageRequestOperation.h" + #import #if __IPHONE_OS_VERSION_MIN_REQUIRED #import -#import "AFImageRequestOperation.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. From 13bc4cfc41d389d9d4f80f6134b0e2ff6ea04dc3 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:41:53 -0500 Subject: [PATCH 34/65] Fixing pre-processor directives for XML request operation --- AFNetworking/AFXMLRequestOperation.m | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFXMLRequestOperation.m b/AFNetworking/AFXMLRequestOperation.m index d57374a..f2aec27 100644 --- a/AFNetworking/AFXMLRequestOperation.m +++ b/AFNetworking/AFXMLRequestOperation.m @@ -134,7 +134,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() { _responseXMLParser.delegate = nil; [_responseXMLParser release]; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED [_responseXMLDocument release]; #endif @@ -151,7 +151,7 @@ static dispatch_queue_t xml_request_operation_processing_queue() { return _responseXMLParser; } -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +#if __MAC_OS_X_VERSION_MIN_REQUIRED - (NSXMLDocument *)responseXMLDocument { if (!_responseXMLDocument && [self isFinished]) { NSError *error = nil; @@ -181,11 +181,19 @@ static dispatch_queue_t xml_request_operation_processing_queue() { 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 From 60ccf59d106d19c9a36ed76f1e46784d26b588fd Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:42:22 -0500 Subject: [PATCH 35/65] Removing Info.plist from 'Copy Bundle Resources' Build Phase --- .../AFNetworking Mac Example.xcodeproj/project.pbxproj | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index cff18be..c084ce3 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -17,7 +17,6 @@ F897DE7C142CFEDC000DDD35 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F8A27AC6142CFE1300F5E0D6 /* Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = F8A27AB1142CFE1300F5E0D6 /* Info.plist */; }; 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 */; }; @@ -92,14 +91,14 @@ F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */, F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */, F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */, - F897DE6D142CFEDC000DDD35 /* AFImageCache.h */, - F897DE6E142CFEDC000DDD35 /* AFImageCache.m */, F897DE6F142CFEDC000DDD35 /* AFImageRequestOperation.h */, F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */, - F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */, - F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */, + F897DE6D142CFEDC000DDD35 /* AFImageCache.h */, + F897DE6E142CFEDC000DDD35 /* AFImageCache.m */, F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */, F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */, + F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */, + F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */, ); name = AFNetworking; path = ../../AFNetworking; @@ -257,7 +256,6 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - F8A27AC6142CFE1300F5E0D6 /* Info.plist in Resources */, F8A27AC9142CFE1300F5E0D6 /* Credits.rtf in Resources */, F8A27ACA142CFE1300F5E0D6 /* MainMenu.xib in Resources */, ); From 440b403f39ac353aa8cd79779ee547fb4966c974 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:44:39 -0500 Subject: [PATCH 36/65] Adding additional pre-processor directives for network activity indicator manager --- AFNetworking/AFNetworkActivityIndicatorManager.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/AFNetworking/AFNetworkActivityIndicatorManager.h b/AFNetworking/AFNetworkActivityIndicatorManager.h index 31b1fb8..d054f17 100644 --- a/AFNetworking/AFNetworkActivityIndicatorManager.h +++ b/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -22,11 +22,14 @@ #import +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import + /** `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. */ - -#if __IPHONE_OS_VERSION_MIN_REQUIRED @interface AFNetworkActivityIndicatorManager : NSObject { @private NSInteger _activityCount; From f4e24f223f3c1ea6186e8ea261fbfc297366d939 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:51:23 -0500 Subject: [PATCH 37/65] Adding Xcode Workspace --- AFNetworking.xcworkspace/contents.xcworkspacedata | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 AFNetworking.xcworkspace/contents.xcworkspacedata diff --git a/AFNetworking.xcworkspace/contents.xcworkspacedata b/AFNetworking.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..4db21e3 --- /dev/null +++ b/AFNetworking.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + From d2be778f9c7ee1f8dd27828567341f7f8af6522b Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:52:16 -0500 Subject: [PATCH 38/65] Adding missing early return in setCompletionBlock: --- AFNetworking/AFURLConnectionOperation.m | 1 + 1 file changed, 1 insertion(+) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 30e04e8..518213c 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -145,6 +145,7 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - (void)setCompletionBlock:(void (^)(void))block { if (!block) { [super setCompletionBlock:nil]; + return; } __block id _blockSelf = self; From d263d0d73d459fab27a159886e3dbcef49872711 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:59:00 -0500 Subject: [PATCH 39/65] Adding AFURLConnectionOperation to main header --- AFNetworking/AFNetworking.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFNetworking.h b/AFNetworking/AFNetworking.h index 3deeec6..82285b3 100644 --- a/AFNetworking/AFNetworking.h +++ b/AFNetworking/AFNetworking.h @@ -23,6 +23,8 @@ #import #import +#import + #import #import #import From 4d4847d5d879f52bb96106fbb120591e86a8b907 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 10:59:28 -0500 Subject: [PATCH 40/65] Removing user-specific Xcode settings --- .../xcdebugger/Breakpoints.xcbkptlist | 5 -- .../AFNetworking iOS Example.xcscheme | 75 ------------------- .../xcschemes/xcschememanagement.plist | 22 ------ 3 files changed, 102 deletions(-) delete mode 100644 iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist delete mode 100644 iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme delete mode 100644 iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist deleted file mode 100644 index 05301bc..0000000 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme deleted file mode 100644 index dc62418..0000000 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 4e24393..0000000 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - SchemeUserState - - AFNetworking iOS Example.xcscheme - - orderHint - 1 - - - SuppressBuildableAutocreation - - F8E4695F1395739C00DB05C8 - - primary - - - - - From f3029262dfc32a7cb0f98154ea3af41ffdfed416 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 12:25:37 -0500 Subject: [PATCH 41/65] Initial implementation of Mac example application --- .../project.pbxproj | 90 +++-- Mac Example/Classes/AFGowallaAPIClient.h | 31 ++ Mac Example/Classes/AFGowallaAPIClient.m | 61 +++ .../Controllers/NearbySpotsController.h | 30 ++ .../Controllers/NearbySpotsController.m | 120 ++++++ Mac Example/Classes/Models/Spot.h | 43 +++ Mac Example/Classes/Models/Spot.m | 78 ++++ Mac Example/Images/placeholder-stamp.png | Bin 0 -> 3968 bytes Mac Example/en.lproj/MainMenu.xib | 349 +++++++++++++++++- .../xcschemes/AFNetworkingExample.xcscheme | 75 ++++ .../xcschemes/xcschememanagement.plist | 22 ++ iOS Example/Classes/AFGowallaAPIClient.m | 6 +- iOS Example/Classes/Models/Spot.h | 4 +- iOS Example/Classes/Models/Spot.m | 2 +- 14 files changed, 866 insertions(+), 45 deletions(-) create mode 100644 Mac Example/Classes/AFGowallaAPIClient.h create mode 100644 Mac Example/Classes/AFGowallaAPIClient.m create mode 100644 Mac Example/Classes/Controllers/NearbySpotsController.h create mode 100644 Mac Example/Classes/Controllers/NearbySpotsController.m create mode 100644 Mac Example/Classes/Models/Spot.h create mode 100644 Mac Example/Classes/Models/Spot.m create mode 100644 Mac Example/Images/placeholder-stamp.png create mode 100644 iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme create mode 100644 iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index c084ce3..4fa95be 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -10,6 +10,11 @@ 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"; }; }; @@ -32,6 +37,14 @@ F87A15A11444926900318955 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFXMLRequestOperation.m; sourceTree = ""; }; F87A15A31444927300318955 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFPropertyListRequestOperation.h; sourceTree = ""; }; F87A15A41444927300318955 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFPropertyListRequestOperation.m; sourceTree = ""; }; + F87A15C51444A30800318955 /* AFGowallaAPIClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFGowallaAPIClient.h; sourceTree = ""; }; + F87A15C61444A30800318955 /* AFGowallaAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFGowallaAPIClient.m; sourceTree = ""; }; + F87A15C81444A30800318955 /* NearbySpotsController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NearbySpotsController.h; sourceTree = ""; }; + F87A15C91444A30800318955 /* NearbySpotsController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NearbySpotsController.m; sourceTree = ""; }; + F87A15CB1444A30800318955 /* Spot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Spot.h; sourceTree = ""; }; + F87A15CC1444A30800318955 /* Spot.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Spot.m; sourceTree = ""; }; + 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 = ""; }; F897DE69142CFEDC000DDD35 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPClient.h; sourceTree = ""; }; F897DE6A142CFEDC000DDD35 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPClient.m; sourceTree = ""; }; F897DE6B142CFEDC000DDD35 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPRequestOperation.h; sourceTree = ""; }; @@ -68,6 +81,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + F87A15D11444A3EB00318955 /* CoreLocation.framework in Frameworks */, F8CEEB6F142CEC6E00247B03 /* Cocoa.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -75,6 +89,43 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + F87A15C41444A30800318955 /* Classes */ = { + isa = PBXGroup; + children = ( + F87A15C51444A30800318955 /* AFGowallaAPIClient.h */, + F87A15C61444A30800318955 /* AFGowallaAPIClient.m */, + F87A15C71444A30800318955 /* Controllers */, + F87A15CA1444A30800318955 /* Models */, + ); + path = Classes; + sourceTree = ""; + }; + F87A15C71444A30800318955 /* Controllers */ = { + isa = PBXGroup; + children = ( + F87A15C81444A30800318955 /* NearbySpotsController.h */, + F87A15C91444A30800318955 /* NearbySpotsController.m */, + ); + path = Controllers; + sourceTree = ""; + }; + F87A15CA1444A30800318955 /* Models */ = { + isa = PBXGroup; + children = ( + F87A15CB1444A30800318955 /* Spot.h */, + F87A15CC1444A30800318955 /* Spot.m */, + ); + path = Models; + sourceTree = ""; + }; + F87A15DA1444A86600318955 /* Images */ = { + isa = PBXGroup; + children = ( + F87A15DB1444A86600318955 /* placeholder-stamp.png */, + ); + path = Images; + sourceTree = ""; + }; F897DE68142CFEDC000DDD35 /* AFNetworking */ = { isa = PBXGroup; children = ( @@ -104,37 +155,6 @@ path = ../../AFNetworking; sourceTree = ""; }; - F8A27AB4142CFE1300F5E0D6 /* Classes */ = { - isa = PBXGroup; - children = ( - F8A27AB5142CFE1300F5E0D6 /* Controllers */, - F8A27AB6142CFE1300F5E0D6 /* Models */, - F8A27AB7142CFE1300F5E0D6 /* Views */, - ); - path = Classes; - sourceTree = ""; - }; - F8A27AB5142CFE1300F5E0D6 /* Controllers */ = { - isa = PBXGroup; - children = ( - ); - path = Controllers; - sourceTree = ""; - }; - F8A27AB6142CFE1300F5E0D6 /* Models */ = { - isa = PBXGroup; - children = ( - ); - path = Models; - sourceTree = ""; - }; - F8A27AB7142CFE1300F5E0D6 /* Views */ = { - isa = PBXGroup; - children = ( - ); - path = Views; - sourceTree = ""; - }; F8A27ABD142CFE1300F5E0D6 /* Vendor */ = { isa = PBXGroup; children = ( @@ -163,6 +183,7 @@ F8A27AC5142CFE1300F5E0D6 /* AppDelegate.h */, F8A27AB9142CFE1300F5E0D6 /* Credits.rtf */, F8A27ABB142CFE1300F5E0D6 /* MainMenu.xib */, + F87A15DA1444A86600318955 /* Images */, ); name = "Supporting Files"; sourceTree = ""; @@ -170,7 +191,7 @@ F8CEEB5F142CEC6E00247B03 = { isa = PBXGroup; children = ( - F8A27AB4142CFE1300F5E0D6 /* Classes */, + F87A15C41444A30800318955 /* Classes */, F8A27ACD142CFE3000F5E0D6 /* Supporting Files */, F8A27ABD142CFE1300F5E0D6 /* Vendor */, F8CEEB6D142CEC6E00247B03 /* Frameworks */, @@ -189,6 +210,7 @@ F8CEEB6D142CEC6E00247B03 /* Frameworks */ = { isa = PBXGroup; children = ( + F87A15D01444A3EB00318955 /* CoreLocation.framework */, F8CEEB6E142CEC6E00247B03 /* Cocoa.framework */, F8CEEB70142CEC6E00247B03 /* Other Frameworks */, ); @@ -258,6 +280,7 @@ files = ( F8A27AC9142CFE1300F5E0D6 /* Credits.rtf in Resources */, F8A27ACA142CFE1300F5E0D6 /* MainMenu.xib in Resources */, + F87A15DD1444A86600318955 /* placeholder-stamp.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -281,6 +304,9 @@ 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; }; diff --git a/Mac Example/Classes/AFGowallaAPIClient.h b/Mac Example/Classes/AFGowallaAPIClient.h new file mode 100644 index 0000000..5fabb8c --- /dev/null +++ b/Mac Example/Classes/AFGowallaAPIClient.h @@ -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 +#import "AFHTTPClient.h" + +extern NSString * const kAFGowallaClientID; +extern NSString * const kAFGowallaBaseURLString; + +@interface AFGowallaAPIClient : AFHTTPClient ++ (AFGowallaAPIClient *)sharedClient; +@end diff --git a/Mac Example/Classes/AFGowallaAPIClient.m b/Mac Example/Classes/AFGowallaAPIClient.m new file mode 100644 index 0000000..53c7f02 --- /dev/null +++ b/Mac Example/Classes/AFGowallaAPIClient.m @@ -0,0 +1,61 @@ +// 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]]; + + // 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 diff --git a/Mac Example/Classes/Controllers/NearbySpotsController.h b/Mac Example/Classes/Controllers/NearbySpotsController.h new file mode 100644 index 0000000..d70623f --- /dev/null +++ b/Mac Example/Classes/Controllers/NearbySpotsController.h @@ -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 +#import + +@interface NearbySpotsController : NSObject + +@property (strong) IBOutlet NSTableView *tableView; + +@end diff --git a/Mac Example/Classes/Controllers/NearbySpotsController.m b/Mac Example/Classes/Controllers/NearbySpotsController.m new file mode 100644 index 0000000..11dc74a --- /dev/null +++ b/Mac Example/Classes/Controllers/NearbySpotsController.m @@ -0,0 +1,120 @@ +// 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 { + [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]; +} + +- (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 indexSetWithIndexesInRange:NSMakeRange(0, 2)]]; + }]; + [self.imageOperationQueue addOperation:operation]; + + image = [NSImage imageNamed:@"placeholder-stamp.png"]; + } + + return image; + } else { + return spot.name; + } +} + +@end diff --git a/Mac Example/Classes/Models/Spot.h b/Mac Example/Classes/Models/Spot.h new file mode 100644 index 0000000..e3c9954 --- /dev/null +++ b/Mac Example/Classes/Models/Spot.h @@ -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 +#import + +@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 diff --git a/Mac Example/Classes/Models/Spot.m b/Mac Example/Classes/Models/Spot.m new file mode 100644 index 0000000..e93e70a --- /dev/null +++ b/Mac Example/Classes/Models/Spot.m @@ -0,0 +1,78 @@ +// 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 { + + NSLog(@"GET"); + 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 diff --git a/Mac Example/Images/placeholder-stamp.png b/Mac Example/Images/placeholder-stamp.png new file mode 100644 index 0000000000000000000000000000000000000000..7aafe3ddaac4e304926d9e84529f82b46e169569 GIT binary patch literal 3968 zcmV-`4}b89P)X+uL$Nkc;* zP;zf(X>4Tx0C)kNmUmQB*%pV-y*Itk5+Wca^cs2zAksTX6$DXM^`x7XQc?|s+0 z08spb1j2M!0f022SQPH-!CVp(%f$Br7!UytSOLJ{W@ZFO_(THK{JlMynW#v{v-a*T zfMmPdEWc1DbJqWVks>!kBnAKqMb$PuekK>?0+ds;#ThdH1j_W4DKdsJG8Ul;qO2n0 z#IJ1jr{*iW$(WZWsE0n`c;fQ!l&-AnmjxZO1uWyz`0VP>&nP`#itsL#`S=Q!g`M=rU9)45( zJ;-|dRq-b5&z?byo>|{)?5r=n76A4nTALlSzLiw~v~31J<>9PP?;rs31pu_(obw)r zY+jPY;tVGXi|p)da{-@gE-UCa`=5eu%D;v=_nFJ?`&K)q7e9d`Nfk3?MdhZarb|T3 z%nS~f&t(1g5dY)AIcd$w!z`Siz!&j_=v7hZlnI21XuE|xfmo0(WD10T)!}~_HYW!e zew}L+XmwuzeT6wtxJd`dZ#@7*BLgIEKY9Xv>st^p3dp{^Xswa2bB{85{^$B13tWnB z;Y>jyQ|9&zk7RNsqAVGs--K+z0uqo1bf5|}fi5rtEMN^BfHQCd-XH*kfJhJnmIE$G z0%<@5vOzxB0181d*a3EfYH$G5fqKvcPJ%XY23!PJzzuK<41h;K3WmW;Fah3yX$XSw z5EY_9s*o0>51B&N5F1(uc|$=^I1~fLLy3?Ol0f;;Ca4%HgQ}rJP(Ab`bQ-z{U4#0d z2hboi2K@njgb|nm(_szR0JebHusa+GN5aeCM0gdP2N%HG;Yzp`J`T6S7vUT504#-H z!jlL<$Or?`Mpy_N@kBz9SR?@vA#0H$qyni$nvf2p8@Y{0k#Xb$28W?xm>3qu8RLgp zjNxKdVb)?wFx8l2m{v>|<~C*!GlBVnrDD~wrdTJeKXwT=5u1%I#8zOBU|X=4u>;s) z>^mF|$G{ol9B_WP7+f-LHLe7=57&&lfa}8z;U@8Tyei%l?}87(bMRt(A-)QK9Dg3) zj~~XrCy)tR1Z#p1A(kK{Y$Q|=8VKhI{e%(1G*N-5Pjn)N5P8I0VkxnX*g?EW941ba z6iJ387g8iCnY4jaNopcpCOsy-A(P2EWJhusSwLP-t|XrzUnLKcKTwn?CKOLf97RIe zPB}`sKzTrUL#0v;sBY9)s+hW+T2H-1eM)^VN0T#`^Oxhvt&^*fYnAJldnHel*Ozyf zUoM{~Um<@={-*r60#U(0!Bc^wuvVc);k3d%g-J!4qLpHZVwz%!VuRu}#Ze`^l7W)9 z5>Kf>>9Eozr6C$Z)1`URxU@~QI@)F0FdauXr2Es8>BaOP=)Lp_WhG@>R;lZ?BJkMlIuMhw8ApiF&yDYW2hFJ?fJhni{?u z85&g@mo&yT8JcdI$(rSw=QPK(Xj%)k1X|@<=e1rim6`6$RAwc!i#egKuI;BS(LSWz zt39n_sIypSqfWEV6J3%nTQ@-4i zi$R;gsG*9XzhRzXqv2yCs*$VFDx+GXJH|L;wsDH_KI2;^u!)^Xl1YupO;gy^-c(?^ z&$Q1BYvyPsG^;hc$D**@Sy`+`)}T4VJji^bd7Jqw3q6Zii=7tT7GEswEK@D(EFW1Z zSp`^awCb?>!`j4}Yh7b~$A)U-W3$et-R8BesV(1jzwLcHnq9En7Q0Tn&-M=XBKs!$ zF$X<|c!#|X_tWYh)GZit z(Q)Cp9CDE^WG;+fcyOWARoj*0TI>4EP1lX*cEoMO-Pk?Z{kZ!p4@(b`M~lalr<3Oz z&kJ6Nm#vN_+kA5{dW4@^Vjg_`q%qU1ULk& z3Fr!>1V#i_2R;ij2@(Z$1jE4r!MlPVFVbHmT+|iPIq0wy5aS{>yK?9ZAjVh%SOwMWgFjair&;wpi!{CU}&@N=Eg#~ zLQ&zpEzVmGY{hI9Z0+4-0xS$$Xe-OToc?Y*V;rTcf_ zb_jRe-RZjXSeas3UfIyD;9afd%<`i0x4T#DzE)vdabOQ=k7SRuGN`h>O0Q~1)u-yD z>VX=Mn&!Rgd$;YK+Q-}1zu#?t(*cbG#Ronf6db&N$oEidtwC+YVcg-Y!_VuY>bk#Y ze_ww@?MU&F&qswvrN_dLb=5o6*Egs)ls3YRlE$&)amR1{;Ppd$6RYV^Go!iq1UMl% z@#4q$AMc(FJlT1QeX8jv{h#)>&{~RGq1N2iiMFIRX?sk2-|2wUogK~{EkB$8eDsX= znVPf8XG_nK&J~=SIiGia@9y}|z3FhX{g&gcj=lwb=lWgyFW&aLedUh- zof`v-2Kw$UzI*>(+&$@i-u=-BsSjR1%z8NeX#HdC`Hh-Z(6xI-`hmHDqv!v)W&&nrf>M(RhcN6(D;jNN*%^u_SYjF;2ng}*8Ow)d6M ztDk;%`@Lsk$;9w$(d(H%O5UixIr`T2ZRcd@y(Ol!$uqRMAs+p<2yh z-9t=6AzKfkc=DoR@KO;C6ufvS3bjI@Q0b+ZG>J)ex0~$0ncW$`Z<04`r>UFNC7G3d zF!|=qd+hvv@0+(XvoD-!noy6DNF-!cmBs{t9|Il+Ie;Jlca-Cxl|CO&Q^3Es@NBE5 zVcsz+=3FkPUyH}%T0PFs{TGo$G7(TgIwJsomKV4&o)^55Btoml12RUB>H!W-wnR+G z=klQGWhfR3plLc7Mr9L)u2sPJE(iKtJQ`0uuGC|R#FDYru-P3GMD9I75ZYC*3Vy#2 zL{S2s=WKW;!Qj}SQ8Ww_%4HqW=?vsHb5N;NvgL{~wFs-9%tU7}dwVN;5*Z&K7fzl$ z_7>0clcFT{V8PK>5T3Wr>IAQa!o&>2fI_|qD=RBd*2^ncpSXVg=9jaxvz1z(!P<8% zaw(Y@PIy(xdz&S&S9o?}XWYt?0UOy3SX)bBw#vU3jpAz;qwzb=zB|=- zB{DNJ^|IU|ek02*p8jxOT?L#_OlWc89?qjuUMrPfkHtRt-r3JtuPJin%B6FHD17Gg z`+3Sly)xhgan?zQGLuQCjY_%l&iV5fzi{@cuK%k@GWqcvlHBrDu)7P|@lx6^2?j_q zS-jL%|6T)KE4>+we)u(ObH+!CB$Jb)DDg{YSEuarb?mzY10|VE=02>it!pTAIvSn$ zjkQ(Bt*@KvBe*}Aob1Qx@Pn$V2P#2WbQRD*5(_aAn*-OXJ|se4vA!1Nsvz>gP;bwH zWuh9EWQc{Bh>aMl+iCwHkyEFSzmNBYkw_%$3JC^GGQ>n|#K?}b_`n>wd^r*Fwzc04 zg?i*xkM)Se`ne_+@&#C4UePu;vQJ#N5MO3s4`igHBk&O#%Sx-l+FcikjTniw8qUs0 z5+49Ps&BckzgNOi-N$wNx~{{$#U(wT%Y>ra51MvHJl?>&NG#zai0i#MQizq9r>CbQ#B7Q9eBEbp0yRW7 z*g#WOh&db%zG91by=|}J+NiW_9N0FD*IK`%81wNHA|(stlRGgzkLo()4=0V4LV?ngnIh3nM}s+&?q~Z^nK_F z^;zJS$iTqUKjMO8LtS1p74V-7;Hkp{KiL^Mbm+;cBS)S!X-T+I3b76i4V#h3;b~h0 zcjixwp87o8AAyCx7NJ-yy4Hu-h>=)FkH7FKu@kJlK7#u)Zdd2$Z=Shv<5w^_6PKjh zaWc7M YES - NSWindowTemplate NSView NSMenu + NSScrollView + NSWindowTemplate NSMenuItem + NSTableView + NSTextFieldCell + NSImageCell + NSTableColumn + NSScroller NSCustomObject @@ -1317,19 +1323,218 @@ 15 2 - {{335, 390}, {480, 360}} + {{50, 538}, {375, 500}} 1954021376 AFNetworking Mac Example NSWindow + {375, 1280} + {375, 200} - + 256 - {480, 360} + + YES + + + 274 + + YES + + + 2304 + + YES + + + 256 + {373, 498} + + + + _NS:1197 + YES + + + -2147483392 + {{224, 0}, {16, 17}} + _NS:1202 + + + YES + + 129.5078125 + 100 + 130 + + 75628096 + 2048 + + + LucidaGrande + 11 + 3100 + + + 3 + MC4zMzMzMzI5ODU2AA + + + 6 + System + headerTextColor + + 3 + MAA + + + + + 67239424 + 33554432 + + LucidaGrande + 13 + 1044 + + _NS:4045 + 1 + 0 + 0 + NO + + 3 + YES + YES + + + + 223 + 40 + 1000 + + 75628096 + 2048 + + + + + + + 337772032 + 0 + Text Cell + + LucidaGrande + 16 + 16 + + + + 6 + System + controlBackgroundColor + + 3 + MC42NjY2NjY2NjY3AA + + + + 6 + System + controlTextColor + + + + 3 + YES + YES + + + + 10 + 10 + + 3 + MQA + + + 6 + System + gridColor + + 3 + MC41AA + + + 60 + 373293056 + + + 4 + 15 + 0 + YES + 0 + 1 + + + {{1, 1}, {373, 498}} + + + + _NS:1195 + + + 4 + + + + -2147483392 + {{224, 17}, {15, 102}} + + + + _NS:1214 + + _doScroller: + 0.99815157116451014 + + + + -2147483392 + {{1, 526}, {374, 15}} + + + + _NS:1216 + 1 + + _doScroller: + 0.99733333333333329 + + + {375, 500} + + + + _NS:1193 + 133682 + + + + QSAAAEEgAABCjAAAQowAAA + + + {375, 500} + + + {{0, 0}, {1920, 1178}} - {10000000000000, 10000000000000} + {375, 222} + {375, 1302} YES @@ -1338,6 +1543,9 @@ NSFontManager + + NearbySpotsController + @@ -2022,6 +2230,30 @@ 535 + + + tableView + + + + 550 + + + + dataSource + + + + 551 + + + + delegate + + + + 552 + @@ -2572,6 +2804,10 @@ 372 + + YES + + @@ -3065,6 +3301,70 @@ + + 537 + + + YES + + + + + + + + 538 + + + + + 540 + + + + + 541 + + + YES + + + + + + + 542 + + + YES + + + + + + 543 + + + YES + + + + + + 544 + + + + + 546 + + + + + 549 + + + @@ -3211,6 +3511,15 @@ 516.IBPluginDependency 517.IBPluginDependency 534.IBPluginDependency + 537.IBPluginDependency + 538.IBPluginDependency + 540.IBPluginDependency + 541.IBPluginDependency + 542.IBPluginDependency + 543.IBPluginDependency + 544.IBPluginDependency + 546.IBPluginDependency + 549.IBPluginDependency 56.IBPluginDependency 57.IBPluginDependency 58.IBPluginDependency @@ -3382,6 +3691,15 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin @@ -3396,7 +3714,7 @@ - 535 + 554 @@ -3487,6 +3805,25 @@ ./Classes/NSDocument.h + + NearbySpotsController + NSObject + + tableView + NSTableView + + + tableView + + tableView + NSTableView + + + + IBProjectSource + ./Classes/NearbySpotsController.h + + 0 diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme new file mode 100644 index 0000000..19af009 --- /dev/null +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..ab5d718 --- /dev/null +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,22 @@ + + + + + SchemeUserState + + AFNetworkingExample.xcscheme + + orderHint + 1 + + + SuppressBuildableAutocreation + + F8E4695F1395739C00DB05C8 + + primary + + + + + diff --git a/iOS Example/Classes/AFGowallaAPIClient.m b/iOS Example/Classes/AFGowallaAPIClient.m index e83a320..4f0bb3d 100644 --- a/iOS Example/Classes/AFGowallaAPIClient.m +++ b/iOS Example/Classes/AFGowallaAPIClient.m @@ -47,6 +47,8 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; return nil; } + [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; + // X-Gowalla-API-Key HTTP Header; see http://api.gowalla.com/api/docs [self setDefaultHeader:@"X-Gowalla-API-Key" value:kAFGowallaClientID]; @@ -55,9 +57,7 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; // X-UDID HTTP Header [self setDefaultHeader:@"X-UDID" value:[[UIDevice currentDevice] uniqueIdentifier]]; - - [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; - + return self; } diff --git a/iOS Example/Classes/Models/Spot.h b/iOS Example/Classes/Models/Spot.h index 3cee711..80a5ee7 100644 --- a/iOS Example/Classes/Models/Spot.h +++ b/iOS Example/Classes/Models/Spot.h @@ -23,8 +23,6 @@ #import #import -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 diff --git a/iOS Example/Classes/Models/Spot.m b/iOS Example/Classes/Models/Spot.m index 5d9675a..bd7272a 100644 --- a/iOS Example/Classes/Models/Spot.m +++ b/iOS Example/Classes/Models/Spot.m @@ -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"]; From b626edf4905eb0215c74788123d2786d59d89160 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 12:26:21 -0500 Subject: [PATCH 42/65] Removing dispatch to main queue to set completion block, since that causes deadlock in (at least) iOS 5 and Mac OS 10.7 --- AFNetworking/AFURLConnectionOperation.m | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index 518213c..d82369b 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -145,17 +145,13 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - (void)setCompletionBlock:(void (^)(void))block { if (!block) { [super setCompletionBlock:nil]; - return; - } - - __block id _blockSelf = self; - [super setCompletionBlock:^ { - block(); - - dispatch_async(dispatch_get_main_queue(), ^(void) { + } else { + __block id _blockSelf = self; + [super setCompletionBlock:^ { + block(); [_blockSelf setCompletionBlock:nil]; - }); - }]; + }]; + } } - (NSInputStream *)inputStream { From e46b9e620b4e133653943eb9340964be5695dc15 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 12:26:34 -0500 Subject: [PATCH 43/65] Conditionally adding default user agent header --- AFNetworking/AFHTTPClient.m | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index ad20922..dafca4e 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -20,11 +20,18 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#import "AFHTTPClient.h" -#import "AFJSONRequestOperation.h" -#import "JSONKit.h" +#import -#include +#import "AFHTTPClient.h" +#import "AFHTTPRequestOperation.h" + +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#endif + +#import "JSONKit.h" static NSString * const kAFMultipartFormLineDelimiter = @"\r\n"; // CRLF static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; @@ -93,7 +100,7 @@ static NSString * AFQueryStringFromParameters(NSDictionary *parameters) { static NSString * AFJSONStringFromParameters(NSDictionary *parameters) { NSString *JSONString = nil; -#if __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_4_3 +#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]; @@ -165,9 +172,11 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 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)]]; +#endif self.operationQueue = [[[NSOperationQueue alloc] init] autorelease]; [self.operationQueue setMaxConcurrentOperationCount:kAFHTTPClientDefaultMaxConcurrentOperationCount]; From 4f09d2c1bf3eee35047ce3fc4ed4057f9ea75cb1 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 12:26:49 -0500 Subject: [PATCH 44/65] Rearranging imports, like a pedant --- AFNetworking/AFJSONRequestOperation.m | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index a268cfa..ac98f52 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -21,10 +21,11 @@ // THE SOFTWARE. #import "AFJSONRequestOperation.h" -#import "JSONKit.h" #include +#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) { From 996cc4c8ac3f73b6740b5b5c245c957e94a2d612 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 13:13:16 -0500 Subject: [PATCH 45/65] Minor refactoring and tweaking of Mac example project --- .../Controllers/NearbySpotsController.m | 3 +-- Mac Example/Classes/Models/Spot.m | 4 +--- Mac Example/en.lproj/MainMenu.xib | 22 ++++++++++++------- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/Mac Example/Classes/Controllers/NearbySpotsController.m b/Mac Example/Classes/Controllers/NearbySpotsController.m index 11dc74a..fa83e2f 100644 --- a/Mac Example/Classes/Controllers/NearbySpotsController.m +++ b/Mac Example/Classes/Controllers/NearbySpotsController.m @@ -103,8 +103,7 @@ 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 indexSetWithIndexesInRange:NSMakeRange(0, 2)]]; + [tableView reloadDataForRowIndexes:[NSIndexSet indexSetWithIndex:row] columnIndexes:[NSIndexSet indexSetWithIndex:0]]; }]; [self.imageOperationQueue addOperation:operation]; diff --git a/Mac Example/Classes/Models/Spot.m b/Mac Example/Classes/Models/Spot.m index e93e70a..ae7c577 100644 --- a/Mac Example/Classes/Models/Spot.m +++ b/Mac Example/Classes/Models/Spot.m @@ -49,9 +49,7 @@ 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 { - - NSLog(@"GET"); ++ (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"]; diff --git a/Mac Example/en.lproj/MainMenu.xib b/Mac Example/en.lproj/MainMenu.xib index d99439d..956ae7a 100644 --- a/Mac Example/en.lproj/MainMenu.xib +++ b/Mac Example/en.lproj/MainMenu.xib @@ -1364,9 +1364,9 @@ YES - 129.5078125 - 100 - 130 + 70 + 70 + 70 75628096 2048 @@ -1393,6 +1393,10 @@ 67239424 33554432 + + NSImage + placeholder-stamp + LucidaGrande 13 @@ -1543,7 +1547,7 @@ NSFontManager - + NearbySpotsController @@ -2233,7 +2237,7 @@ tableView - + 550 @@ -2242,7 +2246,7 @@ dataSource - + 551 @@ -2250,7 +2254,7 @@ delegate - + 552 @@ -3362,7 +3366,7 @@ 549 - + @@ -3844,11 +3848,13 @@ YES NSMenuCheckmark NSMenuMixedState + placeholder-stamp YES {9, 8} {7, 2} + {50, 50} From f882beef46f35e8347f29bc81b644bb30ec3f6c9 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 13:21:24 -0500 Subject: [PATCH 46/65] Updating file headers and credits for Mac example project --- Mac Example/AppDelegate.h | 27 ++++++++++++++++++----- Mac Example/AppDelegate.m | 33 ++++++++++++++++++--------- Mac Example/en.lproj/Credits.rtf | 38 +++++++++----------------------- Mac Example/main.m | 27 ++++++++++++++++++----- 4 files changed, 76 insertions(+), 49 deletions(-) diff --git a/Mac Example/AppDelegate.h b/Mac Example/AppDelegate.h index 2c777c5..c5f8f5c 100644 --- a/Mac Example/AppDelegate.h +++ b/Mac Example/AppDelegate.h @@ -1,10 +1,25 @@ +// AppDelegate.h // -// AFNetworking_Mac_ExampleAppDelegate.h -// AFNetworking Mac Example -// -// Created by Mattt Thompson on 11/09/23. -// Copyright 2011年 Gowalla. All rights reserved. -// +// 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 diff --git a/Mac Example/AppDelegate.m b/Mac Example/AppDelegate.m index 99ed16e..570ef2a 100644 --- a/Mac Example/AppDelegate.m +++ b/Mac Example/AppDelegate.m @@ -1,20 +1,33 @@ +// AppDelegate.m // -// AFNetworking_Mac_ExampleAppDelegate.m -// AFNetworking Mac Example -// -// Created by Mattt Thompson on 11/09/23. -// Copyright 2011年 Gowalla. All rights reserved. -// +// 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 -{ - // Insert code here to initialize your application +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + } @end diff --git a/Mac Example/en.lproj/Credits.rtf b/Mac Example/en.lproj/Credits.rtf index 46576ef..f729028 100644 --- a/Mac Example/en.lproj/Credits.rtf +++ b/Mac Example/en.lproj/Credits.rtf @@ -1,29 +1,13 @@ -{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} +{\rtf1\ansi\ansicpg1252\cocoartf1138 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} -\paperw9840\paperh8400 -\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural +{\*\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 Engineering: -\b0 \ - Some people\ -\ - -\b Human Interface Design: -\b0 \ - Some other people\ -\ - -\b Testing: -\b0 \ - Hopefully not nobody\ -\ - -\b Documentation: -\b0 \ - Whoever\ -\ - -\b With special thanks to: -\b0 \ - Mom\ -} +\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} \ No newline at end of file diff --git a/Mac Example/main.m b/Mac Example/main.m index 4fd2746..499e684 100644 --- a/Mac Example/main.m +++ b/Mac Example/main.m @@ -1,10 +1,25 @@ +// main.m // -// main.m -// AFNetworking Mac Example -// -// Created by Mattt Thompson on 11/09/23. -// Copyright 2011年 Gowalla. All rights reserved. -// +// 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 From 23ae78bdd5a4a3f8b27dd0479ef36f2df36397cf Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 13:25:41 -0500 Subject: [PATCH 47/65] Renaming iOS Example target --- .../project.pbxproj | 14 +++++++------- ....xcscheme => AFNetworking iOS Example.xcscheme} | 12 ++++++------ .../xcschemes/xcschememanagement.plist | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) rename iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/{AFNetworkingExample.xcscheme => AFNetworking iOS Example.xcscheme} (87%) diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj index 53eb182..af434a4 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj @@ -275,9 +275,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 */, @@ -287,7 +287,7 @@ ); dependencies = ( ); - name = AFNetworkingExample; + name = "AFNetworking iOS Example"; productName = AFNetworkingExample; productReference = F8E469601395739C00DB05C8 /* AFNetworkingExample.app */; productType = "com.apple.product-type.application"; @@ -301,7 +301,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; @@ -313,7 +313,7 @@ projectDirPath = ""; projectRoot = ""; targets = ( - F8E4695F1395739C00DB05C8 /* AFNetworkingExample */, + F8E4695F1395739C00DB05C8 /* AFNetworking iOS Example */, ); }; /* End PBXProject section */ @@ -428,7 +428,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 */, @@ -437,7 +437,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 */, diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme similarity index 87% rename from iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme rename to iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme index 19af009..dc62418 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworkingExample.xcscheme +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/AFNetworking iOS Example.xcscheme @@ -14,8 +14,8 @@ @@ -41,8 +41,8 @@ @@ -59,8 +59,8 @@ diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist index ab5d718..4e24393 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -4,7 +4,7 @@ SchemeUserState - AFNetworkingExample.xcscheme + AFNetworking iOS Example.xcscheme orderHint 1 From 5f56aebd295603791eaec45218767ba19d892e31 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 13:26:41 -0500 Subject: [PATCH 48/65] Rearranging schemes, like a pedant --- .../mattt.xcuserdatad/xcschemes/xcschememanagement.plist | 2 +- .../mattt.xcuserdatad/xcschemes/xcschememanagement.plist | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist index c675876..b93bb08 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ AFNetworking Mac Example.xcscheme orderHint - 0 + 1 SuppressBuildableAutocreation diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist index 4e24393..41f9f5a 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/xcuserdata/mattt.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ AFNetworking iOS Example.xcscheme orderHint - 1 + 0 SuppressBuildableAutocreation From 840eca217caaad11392e55a6d4ca722bfc0ee4d8 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 15:27:36 -0500 Subject: [PATCH 49/65] Documentation for AFURLConnectionOperation --- AFNetworking/AFURLConnectionOperation.h | 115 +++++++++++++++++++++--- AFNetworking/AFURLConnectionOperation.m | 8 +- 2 files changed, 106 insertions(+), 17 deletions(-) diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 8c620aa..103643d 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -39,7 +39,40 @@ extern NSString * const AFNetworkingOperationDidStartNotification; */ extern NSString * const AFNetworkingOperationDidFinishNotification; - +/** + `AFURLConnectionOperation` 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 + + 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 a 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`. See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. + + One common oversight when setting completion blocks is to forget to check for whether the operation was cancelled. Be sure to handle called operations appropriately (e.g. returning early before parsing response data). + */ @interface AFURLConnectionOperation : NSOperation { @private NSSet *_runLoopModes; @@ -55,19 +88,77 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; NSOutputStream *_outputStream; } -@property (nonatomic, retain) NSSet *runLoopModes; - -@property (readonly, nonatomic, retain) NSURLRequest *request; -@property (readonly, nonatomic, retain) NSURLResponse *response; -@property (readonly, nonatomic, retain) NSError *error; - -@property (readonly, nonatomic, retain) NSData *responseData; -@property (readonly, nonatomic, copy) NSString *responseString; - -@property (nonatomic, retain) NSInputStream *inputStream; -@property (nonatomic, retain) NSOutputStream *outputStream; +///------------------------------- +/// @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; diff --git a/AFNetworking/AFURLConnectionOperation.m b/AFNetworking/AFURLConnectionOperation.m index d82369b..97bf745 100644 --- a/AFNetworking/AFURLConnectionOperation.m +++ b/AFNetworking/AFURLConnectionOperation.m @@ -159,11 +159,9 @@ static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { } - (void)setInputStream:(NSInputStream *)inputStream { - if (inputStream) { - NSMutableURLRequest *mutableRequest = [[self.request mutableCopy] autorelease]; - mutableRequest.HTTPBodyStream = inputStream; - self.request = mutableRequest; - } + NSMutableURLRequest *mutableRequest = [[self.request mutableCopy] autorelease]; + mutableRequest.HTTPBodyStream = inputStream; + self.request = mutableRequest; } - (void)setUploadProgressBlock:(void (^)(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite))block { From e3205b5c6d725aaa45557de6b7a64d543eb4431a Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 15:28:07 -0500 Subject: [PATCH 50/65] Updating iOS example project file --- .../AFNetworking iOS Example.xcodeproj/project.pbxproj | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj index af434a4..a5cf1cc 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj @@ -68,7 +68,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; }; @@ -175,7 +175,7 @@ F8E469611395739C00DB05C8 /* Products */ = { isa = PBXGroup; children = ( - F8E469601395739C00DB05C8 /* AFNetworkingExample.app */, + F8E469601395739C00DB05C8 /* AFNetworking iOS Example.app */, ); name = Products; sourceTree = ""; @@ -289,7 +289,7 @@ ); 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 */ From f04c832f4f25a8039392cec186e18fca6cc3bd05 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 15:46:01 -0500 Subject: [PATCH 51/65] Documentation for AFHTTPRequestOperation --- AFNetworking/AFHTTPRequestOperation.h | 78 ++++++++++----------------- 1 file changed, 28 insertions(+), 50 deletions(-) diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 8e66e54..73ceef8 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -25,35 +25,7 @@ #import "AFHTTPClient.h" /** - `AFHTTPRequestOperation` is an `NSOperation` subclass that implements the `NSURLConnection` delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. - - # 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 - - // - - ### `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 + `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. */ @interface AFHTTPRequestOperation : AFURLConnectionOperation { @private @@ -62,36 +34,42 @@ NSError *_HTTPError; } -@property (readonly, nonatomic, retain) NSHTTPURLResponse *response; +///---------------------------------------------- +/// @name Getting HTTP URL Connection Information +///---------------------------------------------- /** - 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. + The last response received by the operation's connection. + */ +@property (readonly, nonatomic, retain) NSHTTPURLResponse *response; + + +///---------------------------------------------------------- +/// @name Managing And Checking For Acceptable HTTP Responses +///---------------------------------------------------------- + +/** + 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 By default, this is the range 200 to 299, inclusive. */ @property (nonatomic, retain) NSIndexSet *acceptableStatusCodes; + +/** + 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`. + */ +@property (readonly) BOOL hasAcceptableStatusCode; + +/** + 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 + + By default, this is `nil`. + */ @property (nonatomic, retain) NSSet *acceptableContentTypes; -///--------------------------------------- -/// @name Creating HTTP Request Operations -///--------------------------------------- - -//+ (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest -// success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSData *data))success -// failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; - -///------------------------------- -/// @name Validating HTTP Response -///------------------------------- - /** - + 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`. */ -- (BOOL)hasAcceptableStatusCode; - -/** - - */ -- (BOOL)hasAcceptableContentType; +@property (readonly) BOOL hasAcceptableContentType; @end From 340fbf19eb279b13fa5cb14aca38e5e976be6752 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 16:08:46 -0500 Subject: [PATCH 52/65] Documentation for AFHTTPRequestOperation and subclasses Removing public accessor for property list format property --- AFNetworking/AFJSONRequestOperation.h | 30 +++++++++--------- AFNetworking/AFPropertyListRequestOperation.h | 26 ++++++++++++++-- AFNetworking/AFPropertyListRequestOperation.m | 1 - AFNetworking/AFXMLRequestOperation.h | 31 +++++++++++++++++++ 4 files changed, 71 insertions(+), 17 deletions(-) diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index 08d1aee..e3a3148 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -24,10 +24,7 @@ #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. - - @see NSOperation - @see AFHTTPRequestOperation + `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with JSON response data. */ @interface AFJSONRequestOperation : AFHTTPRequestOperation { @private @@ -35,20 +32,25 @@ NSError *_JSONError; } -@property (readonly, nonatomic, retain) id responseJSON; - -///--------------------------------------- -/// @name Creating JSON Request Operations -///--------------------------------------- +///---------------------------- +/// @name Getting Response Data +///---------------------------- /** - 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. + 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. + */ +@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 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. + @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 */ diff --git a/AFNetworking/AFPropertyListRequestOperation.h b/AFNetworking/AFPropertyListRequestOperation.h index 9c2db3e..53c76b5 100644 --- a/AFNetworking/AFPropertyListRequestOperation.h +++ b/AFNetworking/AFPropertyListRequestOperation.h @@ -23,6 +23,9 @@ #import #import "AFHTTPRequestOperation.h" +/** + `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with Property List (plist) response data. + */ @interface AFPropertyListRequestOperation : AFHTTPRequestOperation { @private id _responsePropertyList; @@ -31,13 +34,32 @@ NSError *_propertyListError; } -@property (readonly, nonatomic, retain) id responsePropertyList; -@property (readonly, nonatomic, assign) NSPropertyListFormat propertyListFormat; +///---------------------------- +/// @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 diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index eb2f7c4..4a32fc3 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -101,7 +101,6 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { self.acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; self.propertyListReadOptions = NSPropertyListImmutable; - self.propertyListFormat = NSPropertyListXMLFormat_v1_0; return self; } diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index 2bbde74..4e45c1e 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -25,6 +25,9 @@ #import +/** + `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with XML response data. + */ @interface AFXMLRequestOperation : AFHTTPRequestOperation { @private NSXMLParser *_responseXMLParser; @@ -34,18 +37,46 @@ 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; From 49d5c656873085660b16b6009b92b2cd9ab4d32d Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 16:47:59 -0500 Subject: [PATCH 53/65] Documentation for AFHTTPClient and AFHTTPClientOperation protocol --- AFNetworking/AFHTTPClient.h | 63 +++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 1847fc5..0a3f555 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -26,6 +26,9 @@ @protocol AFHTTPClientOperation; @protocol AFMultipartFormData; +/** + Method used to encode parameters into request body + */ typedef enum { AFFormURLParameterEncoding, AFJSONParameterEncoding, @@ -33,9 +36,23 @@ typedef enum { } AFHTTPClientParameterEncoding; /** - `AFHTTPClient` objects encapsulates the common patterns of communicating with an application, webservice, or API. It encapsulates persistent information, like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations. + `AFHTTPClient` 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. - In its default implementation, `AFHTTPClient` sets the following HTTP headers: + ## 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. 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`. + + ## Default Headers + + By default, `AFHTTPClient` sets the following HTTP headers: - `Accept: application/json` - `Accept-Encoding: gzip` @@ -43,14 +60,6 @@ typedef enum { - `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 @@ -162,13 +171,17 @@ typedef enum { ///------------------------------- /** - 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 @@ -184,6 +197,8 @@ typedef enum { @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 @@ -289,8 +304,27 @@ typedef enum { #pragma mark - -@protocol AFHTTPClientOperation -+ (BOOL)canProcessRequest:(NSURLRequest *)request; +/** + 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; @@ -300,6 +334,9 @@ typedef enum { /** 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 From a84be8b922a9e61d5d00f1e2ce1e8ec960d9eac0 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 16:48:10 -0500 Subject: [PATCH 54/65] Mass edits and fixes to documentation --- AFNetworking/AFJSONRequestOperation.h | 4 ++-- AFNetworking/AFPropertyListRequestOperation.h | 4 ++-- AFNetworking/AFURLConnectionOperation.h | 2 +- AFNetworking/AFXMLRequestOperation.h | 8 ++++---- AFNetworking/UIImageView+AFNetworking.h | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index e3a3148..bba9742 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -49,8 +49,8 @@ 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 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. + @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 */ diff --git a/AFNetworking/AFPropertyListRequestOperation.h b/AFNetworking/AFPropertyListRequestOperation.h index 53c76b5..23063d8 100644 --- a/AFNetworking/AFPropertyListRequestOperation.h +++ b/AFNetworking/AFPropertyListRequestOperation.h @@ -56,8 +56,8 @@ 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. + @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 */ diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index 103643d..eb17580 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -42,7 +42,7 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; /** `AFURLConnectionOperation` is an `NSOperation` that implements the NSURLConnection delegate methods, and provides a simple block-based interface to asynchronously get the result and context of that operation finishes. - # Subclassing Notes + ## Subclassing Notes 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. diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index 4e45c1e..12c262e 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -57,8 +57,8 @@ 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. + @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 */ @@ -72,8 +72,8 @@ 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. + @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 */ diff --git a/AFNetworking/UIImageView+AFNetworking.h b/AFNetworking/UIImageView+AFNetworking.h index 71ecdc0..08a22dc 100644 --- a/AFNetworking/UIImageView+AFNetworking.h +++ b/AFNetworking/UIImageView+AFNetworking.h @@ -58,8 +58,8 @@ @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:` */ From e7f799484aa0c212c8aefaa96eada724fa3227ff Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 16:55:14 -0500 Subject: [PATCH 55/65] Adding Mac user agent to AFHTTPClient. Thanks to @Sutto (Darcy Laycock) --- AFNetworking/AFHTTPClient.m | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index dafca4e..42b2b40 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -176,6 +176,8 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { #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]; From e9855af89db857fc0c81473d95efc69aa3e583e5 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Tue, 11 Oct 2011 17:07:27 -0500 Subject: [PATCH 56/65] Fixing race condition in UIImageView category with cached images. Thanks @iwat (Chaiwat S.) --- AFNetworking/UIImageView+AFNetworking.m | 1 + 1 file changed, 1 insertion(+) diff --git a/AFNetworking/UIImageView+AFNetworking.m b/AFNetworking/UIImageView+AFNetworking.m index c8d991f..f1ae48a 100644 --- a/AFNetworking/UIImageView+AFNetworking.m +++ b/AFNetworking/UIImageView+AFNetworking.m @@ -92,6 +92,7 @@ static char kAFImageRequestOperationObjectKey; UIImage *cachedImage = [[AFImageCache sharedImageCache] cachedImageForURL:[urlRequest URL] cacheName:nil]; if (cachedImage) { self.image = cachedImage; + self.af_imageRequestOperation = nil; if (success) { success(nil, nil, cachedImage); From b8ca3496f846096ab8ded3d22aac0df716f9779f Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 10:41:59 -0500 Subject: [PATCH 57/65] Adding -unregisterHTTPOperationClass to AFHTTPClient Removing 'Accept: applciation/json' default header from AFHTTPClient Revising documentation for AFHTTPClient --- AFNetworking/AFHTTPClient.h | 35 +++++++++++++++--------- AFNetworking/AFHTTPClient.m | 19 ++++--------- Mac Example/Classes/AFGowallaAPIClient.m | 3 ++ iOS Example/Classes/AFGowallaAPIClient.m | 3 ++ 4 files changed, 33 insertions(+), 27 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 0a3f555..3223b1c 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -54,7 +54,6 @@ typedef enum { 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}` @@ -86,7 +85,7 @@ typedef enum { @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; @@ -113,7 +112,7 @@ typedef enum { @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 */ @@ -123,8 +122,28 @@ typedef enum { /// @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 `requestWithMethod:path:parameters` 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 ///---------------------------------- @@ -367,16 +386,6 @@ typedef enum { */ - (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. diff --git a/AFNetworking/AFHTTPClient.m b/AFNetworking/AFHTTPClient.m index 42b2b40..9a24ce7 100644 --- a/AFNetworking/AFHTTPClient.m +++ b/AFNetworking/AFHTTPClient.m @@ -163,9 +163,6 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { 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"]; @@ -208,6 +205,11 @@ static NSString * AFPropertyListStringFromParameters(NSDictionary *parameters) { return YES; } +- (void)unregisterHTTPOperationClass:(Class)operationClass { + NSString *className = NSStringFromClass(operationClass); + [self.registeredHTTPOperationClassNames removeObject:className]; +} + #pragma mark - - (NSString *)defaultValueForHeader:(NSString *)header { @@ -453,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]; } diff --git a/Mac Example/Classes/AFGowallaAPIClient.m b/Mac Example/Classes/AFGowallaAPIClient.m index 53c7f02..1f0b5e7 100644 --- a/Mac Example/Classes/AFGowallaAPIClient.m +++ b/Mac Example/Classes/AFGowallaAPIClient.m @@ -49,6 +49,9 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; [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]; diff --git a/iOS Example/Classes/AFGowallaAPIClient.m b/iOS Example/Classes/AFGowallaAPIClient.m index 4f0bb3d..6e8f5f4 100644 --- a/iOS Example/Classes/AFGowallaAPIClient.m +++ b/iOS Example/Classes/AFGowallaAPIClient.m @@ -49,6 +49,9 @@ NSString * const kAFGowallaBaseURLString = @"https://api.gowalla.com/"; [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]; From c492d488d87b9d7101cf41cd437f2855130d9c0f Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 10:42:53 -0500 Subject: [PATCH 58/65] Further documentation revisions --- AFNetworking/AFHTTPRequestOperation.h | 2 +- AFNetworking/AFImageCache.h | 2 +- AFNetworking/AFImageRequestOperation.h | 20 +++++++++++++++---- AFNetworking/AFJSONRequestOperation.h | 9 ++++++++- AFNetworking/AFJSONRequestOperation.m | 2 +- AFNetworking/AFPropertyListRequestOperation.h | 8 +++++++- AFNetworking/AFPropertyListRequestOperation.m | 4 ++-- AFNetworking/AFURLConnectionOperation.h | 8 ++++---- AFNetworking/AFXMLRequestOperation.h | 9 ++++++++- 9 files changed, 48 insertions(+), 16 deletions(-) diff --git a/AFNetworking/AFHTTPRequestOperation.h b/AFNetworking/AFHTTPRequestOperation.h index 73ceef8..d93ea67 100644 --- a/AFNetworking/AFHTTPRequestOperation.h +++ b/AFNetworking/AFHTTPRequestOperation.h @@ -39,7 +39,7 @@ ///---------------------------------------------- /** - The last response received by the operation's connection. + The last HTTP response received by the operation's connection. */ @property (readonly, nonatomic, retain) NSHTTPURLResponse *response; diff --git a/AFNetworking/AFImageCache.h b/AFNetworking/AFImageCache.h index 8c16508..94fed9f 100644 --- a/AFNetworking/AFImageCache.h +++ b/AFNetworking/AFImageCache.h @@ -26,7 +26,7 @@ #import /** - `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. */ diff --git a/AFNetworking/AFImageRequestOperation.h b/AFNetworking/AFImageRequestOperation.h index 06e130d..d18b6be 100644 --- a/AFNetworking/AFImageRequestOperation.h +++ b/AFNetworking/AFImageRequestOperation.h @@ -32,10 +32,22 @@ #endif /** - `AFImageRequestOperation` is an `NSOperation` that wraps the callback from `AFHTTPRequestOperation` to create an image from the response body, and optionally cache the image to memory. + `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images. - @see NSOperation - @see AFHTTPRequestOperation + ## 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 { @private @@ -56,7 +68,7 @@ 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 */ diff --git a/AFNetworking/AFJSONRequestOperation.h b/AFNetworking/AFJSONRequestOperation.h index bba9742..b489343 100644 --- a/AFNetworking/AFJSONRequestOperation.h +++ b/AFNetworking/AFJSONRequestOperation.h @@ -24,7 +24,14 @@ #import "AFHTTPRequestOperation.h" /** - `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with JSON response data. + `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data. + + ## 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 { @private diff --git a/AFNetworking/AFJSONRequestOperation.m b/AFNetworking/AFJSONRequestOperation.m index ac98f52..2af8624 100644 --- a/AFNetworking/AFJSONRequestOperation.m +++ b/AFNetworking/AFJSONRequestOperation.m @@ -88,7 +88,7 @@ static dispatch_queue_t json_request_operation_processing_queue() { } + (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 { diff --git a/AFNetworking/AFPropertyListRequestOperation.h b/AFNetworking/AFPropertyListRequestOperation.h index 23063d8..bc02738 100644 --- a/AFNetworking/AFPropertyListRequestOperation.h +++ b/AFNetworking/AFPropertyListRequestOperation.h @@ -24,7 +24,13 @@ #import "AFHTTPRequestOperation.h" /** - `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with Property List (plist) response data. + `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 diff --git a/AFNetworking/AFPropertyListRequestOperation.m b/AFNetworking/AFPropertyListRequestOperation.m index 4a32fc3..01a81b1 100644 --- a/AFNetworking/AFPropertyListRequestOperation.m +++ b/AFNetworking/AFPropertyListRequestOperation.m @@ -85,7 +85,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { } + (NSSet *)defaultAcceptableContentTypes { - return [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; + return [NSSet setWithObjects:@"application/x-plist", nil]; } + (NSSet *)defaultAcceptablePathExtensions { @@ -98,7 +98,7 @@ static dispatch_queue_t property_list_request_operation_processing_queue() { return nil; } - self.acceptableContentTypes = [NSSet setWithObjects:@"application/x-plist", @"application/xml", nil]; + self.acceptableContentTypes = [[self class] defaultAcceptableContentTypes]; self.propertyListReadOptions = NSPropertyListImmutable; diff --git a/AFNetworking/AFURLConnectionOperation.h b/AFNetworking/AFURLConnectionOperation.h index eb17580..210ac43 100644 --- a/AFNetworking/AFURLConnectionOperation.h +++ b/AFNetworking/AFURLConnectionOperation.h @@ -40,7 +40,7 @@ extern NSString * const AFNetworkingOperationDidStartNotification; extern NSString * const AFNetworkingOperationDidFinishNotification; /** - `AFURLConnectionOperation` 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. + `AFURLConnectionOperation` is an `NSOperation` that implements NSURLConnection delegate methods. ## Subclassing Notes @@ -65,13 +65,13 @@ extern NSString * const AFNetworkingOperationDidFinishNotification; ## Class Constructors - Class constructors, or methods that return a 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`. + 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`. See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. + 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. - One common oversight when setting completion blocks is to forget to check for whether the operation was cancelled. Be sure to handle called operations appropriately (e.g. returning early before parsing response data). + @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 diff --git a/AFNetworking/AFXMLRequestOperation.h b/AFNetworking/AFXMLRequestOperation.h index 12c262e..441a841 100644 --- a/AFNetworking/AFXMLRequestOperation.h +++ b/AFNetworking/AFXMLRequestOperation.h @@ -26,7 +26,14 @@ #import /** - `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` that provides functionality to work with XML response data. + `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 From c7af6d7397b10df561a71b15ab500962807e77f2 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 10:52:22 -0500 Subject: [PATCH 59/65] Minor tweaks to Mac example application --- .../project.pbxproj | 12 - .../Controllers/NearbySpotsController.m | 6 +- Mac Example/en.lproj/MainMenu.xib | 2819 ----------------- 3 files changed, 5 insertions(+), 2832 deletions(-) diff --git a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj index 4fa95be..4074804 100644 --- a/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj +++ b/Mac Example/AFNetworking Mac Example.xcodeproj/project.pbxproj @@ -20,8 +20,6 @@ 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"; }; }; - F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.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 */; }; @@ -55,11 +53,7 @@ F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageRequestOperation.m; sourceTree = ""; }; F897DE71142CFEDC000DDD35 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFJSONRequestOperation.h; sourceTree = ""; }; F897DE72142CFEDC000DDD35 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFJSONRequestOperation.m; sourceTree = ""; }; - F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; - F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; F897DE75142CFEDC000DDD35 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = ""; }; - F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = ""; }; - F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = ""; }; F8A27AB1142CFE1300F5E0D6 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; F8A27AB2142CFE1300F5E0D6 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; F8A27AB3142CFE1300F5E0D6 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; @@ -146,10 +140,6 @@ F897DE70142CFEDC000DDD35 /* AFImageRequestOperation.m */, F897DE6D142CFEDC000DDD35 /* AFImageCache.h */, F897DE6E142CFEDC000DDD35 /* AFImageCache.m */, - F897DE76142CFEDC000DDD35 /* UIImageView+AFNetworking.h */, - F897DE77142CFEDC000DDD35 /* UIImageView+AFNetworking.m */, - F897DE73142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.h */, - F897DE74142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m */, ); name = AFNetworking; path = ../../AFNetworking; @@ -299,8 +289,6 @@ F897DE7A142CFEDC000DDD35 /* AFImageCache.m in Sources */, F897DE7B142CFEDC000DDD35 /* AFImageRequestOperation.m in Sources */, F897DE7C142CFEDC000DDD35 /* AFJSONRequestOperation.m in Sources */, - F897DE7D142CFEDC000DDD35 /* AFNetworkActivityIndicatorManager.m in Sources */, - F897DE7E142CFEDC000DDD35 /* UIImageView+AFNetworking.m in Sources */, F87A159F1444926300318955 /* AFURLConnectionOperation.m in Sources */, F87A15A21444926A00318955 /* AFXMLRequestOperation.m in Sources */, F87A15A51444927300318955 /* AFPropertyListRequestOperation.m in Sources */, diff --git a/Mac Example/Classes/Controllers/NearbySpotsController.m b/Mac Example/Classes/Controllers/NearbySpotsController.m index fa83e2f..f699331 100644 --- a/Mac Example/Classes/Controllers/NearbySpotsController.m +++ b/Mac Example/Classes/Controllers/NearbySpotsController.m @@ -59,7 +59,11 @@ return self; } -- (void)awakeFromNib { +- (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]; } diff --git a/Mac Example/en.lproj/MainMenu.xib b/Mac Example/en.lproj/MainMenu.xib index 956ae7a..de1165c 100644 --- a/Mac Example/en.lproj/MainMenu.xib +++ b/Mac Example/en.lproj/MainMenu.xib @@ -85,26 +85,6 @@ - - - Preferences… - , - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - Services @@ -184,1059 +164,6 @@ _NSAppleMenu - - - File - - 1048576 - 2147483647 - - - submenuAction: - - File - - YES - - - New - n - 1048576 - 2147483647 - - - - - - Open… - o - 1048576 - 2147483647 - - - - - - Open Recent - - 1048576 - 2147483647 - - - submenuAction: - - Open Recent - - YES - - - Clear Menu - - 1048576 - 2147483647 - - - - - _NSRecentDocumentsMenu - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Close - w - 1048576 - 2147483647 - - - - - - Save… - s - 1048576 - 2147483647 - - - - - - Revert to Saved - - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Page Setup... - P - 1179648 - 2147483647 - - - - - - - Print… - p - 1048576 - 2147483647 - - - - - - - - - Edit - - 1048576 - 2147483647 - - - submenuAction: - - Edit - - YES - - - Undo - z - 1048576 - 2147483647 - - - - - - Redo - Z - 1179648 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Cut - x - 1048576 - 2147483647 - - - - - - Copy - c - 1048576 - 2147483647 - - - - - - Paste - v - 1048576 - 2147483647 - - - - - - Paste and Match Style - V - 1572864 - 2147483647 - - - - - - Delete - - 1048576 - 2147483647 - - - - - - Select All - a - 1048576 - 2147483647 - - - - - - YES - YES - - - 1048576 - 2147483647 - - - - - - Find - - 1048576 - 2147483647 - - - submenuAction: - - Find - - YES - - - Find… - f - 1048576 - 2147483647 - - - 1 - - - - Find and Replace… - f - 1572864 - 2147483647 - - - 12 - - - - Find Next - g - 1048576 - 2147483647 - - - 2 - - - - Find Previous - G - 1179648 - 2147483647 - - - 3 - - - - Use Selection for Find - e - 1048576 - 2147483647 - - - 7 - - - - Jump to Selection - j - 1048576 - 2147483647 - - - - - - - - - Spelling and Grammar - - 1048576 - 2147483647 - - - submenuAction: - - Spelling and Grammar - - YES - - - Show Spelling and Grammar - : - 1048576 - 2147483647 - - - - - - Check Document Now - ; - 1048576 - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Check Spelling While Typing - - 1048576 - 2147483647 - - - - - - Check Grammar With Spelling - - 1048576 - 2147483647 - - - - - - Correct Spelling Automatically - - 2147483647 - - - - - - - - - Substitutions - - 1048576 - 2147483647 - - - submenuAction: - - Substitutions - - YES - - - Show Substitutions - - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Smart Copy/Paste - f - 1048576 - 2147483647 - - - 1 - - - - Smart Quotes - g - 1048576 - 2147483647 - - - 2 - - - - Smart Dashes - - 2147483647 - - - - - - Smart Links - G - 1179648 - 2147483647 - - - 3 - - - - Text Replacement - - 2147483647 - - - - - - - - - Transformations - - 2147483647 - - - submenuAction: - - Transformations - - YES - - - Make Upper Case - - 2147483647 - - - - - - Make Lower Case - - 2147483647 - - - - - - Capitalize - - 2147483647 - - - - - - - - - Speech - - 1048576 - 2147483647 - - - submenuAction: - - Speech - - YES - - - Start Speaking - - 1048576 - 2147483647 - - - - - - Stop Speaking - - 1048576 - 2147483647 - - - - - - - - - - - - Format - - 2147483647 - - - submenuAction: - - Format - - YES - - - Font - - 2147483647 - - - submenuAction: - - Font - - YES - - - Show Fonts - t - 1048576 - 2147483647 - - - - - - Bold - b - 1048576 - 2147483647 - - - 2 - - - - Italic - i - 1048576 - 2147483647 - - - 1 - - - - Underline - u - 1048576 - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Bigger - + - 1048576 - 2147483647 - - - 3 - - - - Smaller - - - 1048576 - 2147483647 - - - 4 - - - - YES - YES - - - 2147483647 - - - - - - Kern - - 2147483647 - - - submenuAction: - - Kern - - YES - - - Use Default - - 2147483647 - - - - - - Use None - - 2147483647 - - - - - - Tighten - - 2147483647 - - - - - - Loosen - - 2147483647 - - - - - - - - - Ligature - - 2147483647 - - - submenuAction: - - Ligature - - YES - - - Use Default - - 2147483647 - - - - - - Use None - - 2147483647 - - - - - - Use All - - 2147483647 - - - - - - - - - Baseline - - 2147483647 - - - submenuAction: - - Baseline - - YES - - - Use Default - - 2147483647 - - - - - - Superscript - - 2147483647 - - - - - - Subscript - - 2147483647 - - - - - - Raise - - 2147483647 - - - - - - Lower - - 2147483647 - - - - - - - - - YES - YES - - - 2147483647 - - - - - - Show Colors - C - 1048576 - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Copy Style - c - 1572864 - 2147483647 - - - - - - Paste Style - v - 1572864 - 2147483647 - - - - - _NSFontMenu - - - - - Text - - 2147483647 - - - submenuAction: - - Text - - YES - - - Align Left - { - 1048576 - 2147483647 - - - - - - Center - | - 1048576 - 2147483647 - - - - - - Justify - - 2147483647 - - - - - - Align Right - } - 1048576 - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - Writing Direction - - 2147483647 - - - submenuAction: - - Writing Direction - - YES - - - YES - Paragraph - - 2147483647 - - - - - - CURlZmF1bHQ - - 2147483647 - - - - - - CUxlZnQgdG8gUmlnaHQ - - 2147483647 - - - - - - CVJpZ2h0IHRvIExlZnQ - - 2147483647 - - - - - - YES - YES - - - 2147483647 - - - - - - YES - Selection - - 2147483647 - - - - - - CURlZmF1bHQ - - 2147483647 - - - - - - CUxlZnQgdG8gUmlnaHQ - - 2147483647 - - - - - - CVJpZ2h0IHRvIExlZnQ - - 2147483647 - - - - - - - - - YES - YES - - - 2147483647 - - - - - - Show Ruler - - 2147483647 - - - - - - Copy Ruler - c - 1310720 - 2147483647 - - - - - - Paste Ruler - v - 1310720 - 2147483647 - - - - - - - - - - - - View - - 1048576 - 2147483647 - - - submenuAction: - - View - - YES - - - Show Toolbar - t - 1572864 - 2147483647 - - - - - - Customize Toolbar… - - 1048576 - 2147483647 - - - - - - Window @@ -1351,7 +278,6 @@ 256 {373, 498} - _NS:1197 YES @@ -1486,7 +412,6 @@ {{1, 1}, {373, 498}} - _NS:1195 @@ -1498,7 +423,6 @@ -2147483392 {{224, 17}, {15, 102}} - _NS:1214 @@ -1510,8 +434,6 @@ -2147483392 {{1, 526}, {374, 15}} - - _NS:1216 1 @@ -1521,7 +443,6 @@ {375, 500} - _NS:1193 133682 @@ -1533,7 +454,6 @@ {375, 500} - {{0, 0}, {1920, 1178}} @@ -1570,30 +490,6 @@ 39 - - - print: - - - - 86 - - - - runPageLayout: - - - - 87 - - - - clearRecentDocuments: - - - - 127 - orderFrontStandardAboutPanel: @@ -1602,110 +498,6 @@ 142 - - - performClose: - - - - 193 - - - - toggleContinuousSpellChecking: - - - - 222 - - - - undo: - - - - 223 - - - - copy: - - - - 224 - - - - checkSpelling: - - - - 225 - - - - paste: - - - - 226 - - - - stopSpeaking: - - - - 227 - - - - cut: - - - - 228 - - - - showGuessPanel: - - - - 230 - - - - redo: - - - - 231 - - - - selectAll: - - - - 232 - - - - startSpeaking: - - - - 233 - - - - delete: - - - - 235 - performZoom: @@ -1714,86 +506,6 @@ 240 - - - performFindPanelAction: - - - - 241 - - - - centerSelectionInVisibleArea: - - - - 245 - - - - toggleGrammarChecking: - - - - 347 - - - - toggleSmartInsertDelete: - - - - 355 - - - - toggleAutomaticQuoteSubstitution: - - - - 356 - - - - toggleAutomaticLinkDetection: - - - - 357 - - - - saveDocument: - - - - 362 - - - - revertDocumentToSaved: - - - - 364 - - - - runToolbarCustomizationPalette: - - - - 365 - - - - toggleToolbarShown: - - - - 366 - hide: @@ -1818,190 +530,6 @@ 370 - - - newDocument: - - - - 373 - - - - openDocument: - - - - 374 - - - - addFontTrait: - - - - 421 - - - - addFontTrait: - - - - 422 - - - - modifyFont: - - - - 423 - - - - orderFrontFontPanel: - - - - 424 - - - - modifyFont: - - - - 425 - - - - raiseBaseline: - - - - 426 - - - - lowerBaseline: - - - - 427 - - - - copyFont: - - - - 428 - - - - subscript: - - - - 429 - - - - superscript: - - - - 430 - - - - tightenKerning: - - - - 431 - - - - underline: - - - - 432 - - - - orderFrontColorPanel: - - - - 433 - - - - useAllLigatures: - - - - 434 - - - - loosenKerning: - - - - 435 - - - - pasteFont: - - - - 436 - - - - unscript: - - - - 437 - - - - useStandardKerning: - - - - 438 - - - - useStandardLigatures: - - - - 439 - - - - turnOffLigatures: - - - - 440 - - - - turnOffKerning: - - - - 441 - terminate: @@ -2010,94 +538,6 @@ 449 - - - toggleAutomaticSpellingCorrection: - - - - 456 - - - - orderFrontSubstitutionsPanel: - - - - 458 - - - - toggleAutomaticDashSubstitution: - - - - 461 - - - - toggleAutomaticTextReplacement: - - - - 463 - - - - uppercaseWord: - - - - 464 - - - - capitalizeWord: - - - - 467 - - - - lowercaseWord: - - - - 468 - - - - pasteAsPlainText: - - - - 486 - - - - performFindPanelAction: - - - - 487 - - - - performFindPanelAction: - - - - 488 - - - - performFindPanelAction: - - - - 489 - showHelp: @@ -2114,110 +554,6 @@ 495 - - - alignCenter: - - - - 518 - - - - pasteRuler: - - - - 519 - - - - toggleRuler: - - - - 520 - - - - alignRight: - - - - 521 - - - - copyRuler: - - - - 522 - - - - alignJustified: - - - - 523 - - - - alignLeft: - - - - 524 - - - - makeBaseWritingDirectionNatural: - - - - 525 - - - - makeBaseWritingDirectionLeftToRight: - - - - 526 - - - - makeBaseWritingDirectionRightToLeft: - - - - 527 - - - - makeTextWritingDirectionNatural: - - - - 528 - - - - makeTextWritingDirectionLeftToRight: - - - - 529 - - - - makeTextWritingDirectionRightToLeft: - - - - 530 - window @@ -2226,14 +562,6 @@ 532 - - - performFindPanelAction: - - - - 535 - tableView @@ -2295,10 +623,6 @@ YES - - - - @@ -2321,264 +645,6 @@ - - 217 - - - YES - - - - - - 83 - - - YES - - - - - - 81 - - - YES - - - - - - - - - - - - - - - 75 - - - - - 78 - - - - - 72 - - - - - 82 - - - - - 124 - - - YES - - - - - - 77 - - - - - 73 - - - - - 79 - - - - - 112 - - - - - 74 - - - - - 125 - - - YES - - - - - - 126 - - - - - 205 - - - YES - - - - - - - - - - - - - - - - - - - - 202 - - - - - 198 - - - - - 207 - - - - - 214 - - - - - 199 - - - - - 203 - - - - - 197 - - - - - 206 - - - - - 215 - - - - - 218 - - - YES - - - - - - 216 - - - YES - - - - - - 200 - - - YES - - - - - - - - - - - 219 - - - - - 201 - - - - - 204 - - - - - 220 - - - YES - - - - - - - - - - - 213 - - - - - 210 - - - - - 221 - - - - - 208 - - - - - 209 - - - 57 @@ -2589,8 +655,6 @@ - - @@ -2623,16 +687,6 @@ - - 129 - - - - - 143 - - - 236 @@ -2694,108 +748,6 @@ - - 295 - - - YES - - - - - - 296 - - - YES - - - - - - - 297 - - - - - 298 - - - - - 211 - - - YES - - - - - - 212 - - - YES - - - - - - - 195 - - - - - 196 - - - - - 346 - - - - - 348 - - - YES - - - - - - 349 - - - YES - - - - - - - - - - - - 350 - - - - - 351 - - - - - 354 - - - 371 @@ -2814,321 +766,11 @@ - - 375 - - - YES - - - - - - 376 - - - YES - - - - - - - 377 - - - YES - - - - - - 388 - - - YES - - - - - - - - - - - - - - - - - - - - - 389 - - - - - 390 - - - - - 391 - - - - - 392 - - - - - 393 - - - - - 394 - - - - - 395 - - - - - 396 - - - - - 397 - - - YES - - - - - - 398 - - - YES - - - - - - 399 - - - YES - - - - - - 400 - - - - - 401 - - - - - 402 - - - - - 403 - - - - - 404 - - - - - 405 - - - YES - - - - - - - - - - 406 - - - - - 407 - - - - - 408 - - - - - 409 - - - - - 410 - - - - - 411 - - - YES - - - - - - - - 412 - - - - - 413 - - - - - 414 - - - - - 415 - - - YES - - - - - - - - - 416 - - - - - 417 - - - - - 418 - - - - - 419 - - - 420 - - 450 - - - YES - - - - - - 451 - - - YES - - - - - - - - 452 - - - - - 453 - - - - - 454 - - - - - 457 - - - - - 459 - - - - - 460 - - - - - 462 - - - - - 465 - - - - - 466 - - - - - 485 - - - 490 @@ -3157,154 +799,6 @@ - - 496 - - - YES - - - - - - 497 - - - YES - - - - - - - - - - - - - - - 498 - - - - - 499 - - - - - 500 - - - - - 501 - - - - - 502 - - - - - 503 - - - YES - - - - - - 504 - - - - - 505 - - - - - 506 - - - - - 507 - - - - - 508 - - - YES - - - - - - - - - - - - - - 509 - - - - - 510 - - - - - 511 - - - - - 512 - - - - - 513 - - - - - 514 - - - - - 515 - - - - - 516 - - - - - 517 - - - - - 534 - - - 537 @@ -3378,143 +872,30 @@ -1.IBPluginDependency -2.IBPluginDependency -3.IBPluginDependency - 112.IBPluginDependency - 124.IBPluginDependency - 125.IBPluginDependency - 126.IBPluginDependency - 129.IBPluginDependency 130.IBPluginDependency 131.IBPluginDependency 134.IBPluginDependency 136.IBPluginDependency - 143.IBPluginDependency 144.IBPluginDependency 145.IBPluginDependency 149.IBPluginDependency 150.IBPluginDependency 19.IBPluginDependency - 195.IBPluginDependency - 196.IBPluginDependency - 197.IBPluginDependency - 198.IBPluginDependency - 199.IBPluginDependency - 200.IBPluginDependency - 201.IBPluginDependency - 202.IBPluginDependency - 203.IBPluginDependency - 204.IBPluginDependency - 205.IBPluginDependency - 206.IBPluginDependency - 207.IBPluginDependency - 208.IBPluginDependency - 209.IBPluginDependency - 210.IBPluginDependency - 211.IBPluginDependency - 212.IBPluginDependency - 213.IBPluginDependency - 214.IBPluginDependency - 215.IBPluginDependency - 216.IBPluginDependency - 217.IBPluginDependency - 218.IBPluginDependency - 219.IBPluginDependency - 220.IBPluginDependency - 221.IBPluginDependency 23.IBPluginDependency 236.IBPluginDependency 239.IBPluginDependency 24.IBPluginDependency 29.IBPluginDependency - 295.IBPluginDependency - 296.IBPluginDependency - 297.IBPluginDependency - 298.IBPluginDependency - 346.IBPluginDependency - 348.IBPluginDependency - 349.IBPluginDependency - 350.IBPluginDependency - 351.IBPluginDependency - 354.IBPluginDependency 371.IBPluginDependency 371.IBWindowTemplateEditedContentRect 371.NSWindowTemplate.visibleAtLaunch 372.IBPluginDependency - 375.IBPluginDependency - 376.IBPluginDependency - 377.IBPluginDependency - 388.IBPluginDependency - 389.IBPluginDependency - 390.IBPluginDependency - 391.IBPluginDependency - 392.IBPluginDependency - 393.IBPluginDependency - 394.IBPluginDependency - 395.IBPluginDependency - 396.IBPluginDependency - 397.IBPluginDependency - 398.IBPluginDependency - 399.IBPluginDependency - 400.IBPluginDependency - 401.IBPluginDependency - 402.IBPluginDependency - 403.IBPluginDependency - 404.IBPluginDependency - 405.IBPluginDependency - 406.IBPluginDependency - 407.IBPluginDependency - 408.IBPluginDependency - 409.IBPluginDependency - 410.IBPluginDependency - 411.IBPluginDependency - 412.IBPluginDependency - 413.IBPluginDependency - 414.IBPluginDependency - 415.IBPluginDependency - 416.IBPluginDependency - 417.IBPluginDependency - 418.IBPluginDependency - 419.IBPluginDependency 420.IBPluginDependency - 450.IBPluginDependency - 451.IBPluginDependency - 452.IBPluginDependency - 453.IBPluginDependency - 454.IBPluginDependency - 457.IBPluginDependency - 459.IBPluginDependency - 460.IBPluginDependency - 462.IBPluginDependency - 465.IBPluginDependency - 466.IBPluginDependency - 485.IBPluginDependency 490.IBPluginDependency 491.IBPluginDependency 492.IBPluginDependency 494.IBPluginDependency - 496.IBPluginDependency - 497.IBPluginDependency - 498.IBPluginDependency - 499.IBPluginDependency 5.IBPluginDependency - 500.IBPluginDependency - 501.IBPluginDependency - 502.IBPluginDependency - 503.IBPluginDependency - 504.IBPluginDependency - 505.IBPluginDependency - 506.IBPluginDependency - 507.IBPluginDependency - 508.IBPluginDependency - 509.IBPluginDependency - 510.IBPluginDependency - 511.IBPluginDependency - 512.IBPluginDependency - 513.IBPluginDependency - 514.IBPluginDependency - 515.IBPluginDependency - 516.IBPluginDependency - 517.IBPluginDependency - 534.IBPluginDependency 537.IBPluginDependency 538.IBPluginDependency 540.IBPluginDependency @@ -3527,16 +908,6 @@ 56.IBPluginDependency 57.IBPluginDependency 58.IBPluginDependency - 72.IBPluginDependency - 73.IBPluginDependency - 74.IBPluginDependency - 75.IBPluginDependency - 77.IBPluginDependency - 78.IBPluginDependency - 79.IBPluginDependency - 81.IBPluginDependency - 82.IBPluginDependency - 83.IBPluginDependency 92.IBPluginDependency @@ -3559,49 +930,6 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin {{380, 496}, {480, 360}} com.apple.InterfaceBuilder.CocoaPlugin @@ -3624,86 +952,6 @@ com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin - com.apple.InterfaceBuilder.CocoaPlugin @@ -3742,73 +990,6 @@ ./Classes/AppDelegate.h - - NSDocument - - YES - - YES - printDocument: - revertDocumentToSaved: - runPageLayout: - saveDocument: - saveDocumentAs: - saveDocumentTo: - - - YES - id - id - id - id - id - id - - - - YES - - YES - printDocument: - revertDocumentToSaved: - runPageLayout: - saveDocument: - saveDocumentAs: - saveDocumentTo: - - - YES - - printDocument: - id - - - revertDocumentToSaved: - id - - - runPageLayout: - id - - - saveDocument: - id - - - saveDocumentAs: - id - - - saveDocumentTo: - id - - - - - IBProjectSource - ./Classes/NSDocument.h - - NearbySpotsController NSObject From ea05359343d1c321e1ad4009b736a60a98300c46 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 10:54:30 -0500 Subject: [PATCH 60/65] Adding self-deprecating apology for utter lack of command of AppKit --- Mac Example/Classes/Controllers/NearbySpotsController.m | 1 + 1 file changed, 1 insertion(+) diff --git a/Mac Example/Classes/Controllers/NearbySpotsController.m b/Mac Example/Classes/Controllers/NearbySpotsController.m index f699331..a62b5db 100644 --- a/Mac Example/Classes/Controllers/NearbySpotsController.m +++ b/Mac Example/Classes/Controllers/NearbySpotsController.m @@ -98,6 +98,7 @@ 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]; From 207b914545aa8ab54e91a99b74346fe28e9fddfa Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 11:07:01 -0500 Subject: [PATCH 61/65] Improving documentation of AFHTTPClient, especially concerning its automatic content parsing behavior --- AFNetworking/AFHTTPClient.h | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/AFNetworking/AFHTTPClient.h b/AFNetworking/AFHTTPClient.h index 3223b1c..581fc5e 100644 --- a/AFNetworking/AFHTTPClient.h +++ b/AFNetworking/AFHTTPClient.h @@ -40,7 +40,7 @@ typedef enum { ## 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. See `AFHTTPClientOperation` for further details. + 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 @@ -48,7 +48,9 @@ typedef enum { ## 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 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 @@ -129,7 +131,7 @@ typedef enum { @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 `requestWithMethod:path:parameters` 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. + @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` */ @@ -233,14 +235,21 @@ typedef enum { /** 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)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; From 15be99000a0bd56e285aa0517abda124271581c8 Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 11:11:18 -0500 Subject: [PATCH 62/65] Adding AFNetworking.h to iOS example Rearranging iOS example project file list --- .../project.pbxproj | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj index a5cf1cc..15377fc 100644 --- a/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj +++ b/iOS Example/AFNetworking iOS Example.xcodeproj/project.pbxproj @@ -58,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 = ""; }; F8D25D1D1396A9DE00CF3BD6 /* AFGowallaAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFGowallaAPIClient.m; path = Classes/AFGowallaAPIClient.m; sourceTree = ""; }; + F8D7DE781445F354000EF2F3 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../AFNetworking/AFNetworking.h; sourceTree = ""; }; F8DA09C71396AB690057D0CC /* NearbySpotsViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NearbySpotsViewController.h; sourceTree = ""; }; F8DA09C81396AB690057D0CC /* NearbySpotsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NearbySpotsViewController.m; sourceTree = ""; }; F8DA09CA1396AB690057D0CC /* Spot.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Spot.h; sourceTree = ""; }; @@ -101,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 = ""; - }; F8D25D0F1396A9C400CF3BD6 /* JSONKit */ = { isa = PBXGroup; children = ( @@ -230,6 +222,7 @@ F8E469941395744600DB05C8 /* AFNetworking */ = { isa = PBXGroup; children = ( + F8D7DE781445F354000EF2F3 /* AFNetworking.h */, F86E5527143A28F3002B438C /* AFURLConnectionOperation.h */, F86E5528143A28F3002B438C /* AFURLConnectionOperation.m */, F874B5D113E0AA6500B28E3E /* AFHTTPRequestOperation.h */, @@ -246,9 +239,10 @@ 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 = ""; From 70be90652951b7eabe9ccefdc61ff3e9afb31f8b Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 11:11:38 -0500 Subject: [PATCH 63/65] Adding AFNetworkActivityIndicatorManager to AFNetworking.h --- AFNetworking/AFNetworking.h | 1 + 1 file changed, 1 insertion(+) diff --git a/AFNetworking/AFNetworking.h b/AFNetworking/AFNetworking.h index 82285b3..2f8f670 100644 --- a/AFNetworking/AFNetworking.h +++ b/AFNetworking/AFNetworking.h @@ -35,5 +35,6 @@ #import #if __IPHONE_OS_VERSION_MIN_REQUIRED +#import #import #endif From 5d2a0b1c918c4a2c06f54527220b60137e112dbf Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 11:39:40 -0500 Subject: [PATCH 64/65] Updating and revising README to match 0.7 API changes --- README.md | 81 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 42 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 9051354..c5b2e1d 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,41 @@ # 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 -Online documentation is available at http://gowalla.github.com/AFNetworking/. +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 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 From a5387b8963220f9dbea8cbe7eea8a73fb76b1eac Mon Sep 17 00:00:00 2001 From: Mattt Thompson Date: Wed, 12 Oct 2011 11:39:57 -0500 Subject: [PATCH 65/65] Updating PodSpec to 0.7 --- AFNetworking.podspec | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AFNetworking.podspec b/AFNetworking.podspec index 8405520..e30e75b 100644 --- a/AFNetworking.podspec +++ b/AFNetworking.podspec @@ -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'