├── Example ├── Icon.png ├── Default.png ├── Icon@2x.png ├── Default@2x.png ├── Default-568h@2x.png ├── Images │ ├── profile-image-placeholder.png │ └── profile-image-placeholder@2x.png ├── AFNetworking Mac Example.xcodeproj │ ├── project.xcworkspace │ │ └── contents.xcworkspacedata │ └── project.pbxproj ├── AFNetworking iOS Example.xcodeproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── AFNetworking Example.entitlements ├── Prefix.pch ├── Mac-Info.plist ├── Classes │ ├── Controllers │ │ ├── GlobalTimelineViewController.h │ │ └── GlobalTimelineViewController.m │ ├── AFAppDotNetAPIClient.h │ ├── Views │ │ ├── PostTableViewCell.h │ │ └── PostTableViewCell.m │ ├── Models │ │ ├── Post.h │ │ ├── User.h │ │ ├── Post.m │ │ └── User.m │ └── AFAppDotNetAPIClient.m ├── main.m ├── iOS-Info.plist ├── AppDelegate.h └── AppDelegate.m ├── AFNetworking.xcworkspace └── contents.xcworkspacedata ├── AFNetworking.podspec ├── LICENSE ├── AFNetworking ├── AFNetworking.h ├── AFPropertyListRequestOperation.h ├── AFJSONRequestOperation.h ├── AFNetworkActivityIndicatorManager.h ├── UIImageView+AFNetworking.h ├── AFXMLRequestOperation.h ├── AFNetworkActivityIndicatorManager.m ├── AFJSONRequestOperation.m ├── AFImageRequestOperation.h ├── AFPropertyListRequestOperation.m ├── AFHTTPRequestOperation.h ├── UIImageView+AFNetworking.m ├── AFXMLRequestOperation.m ├── AFImageRequestOperation.m ├── AFHTTPRequestOperation.m ├── AFURLConnectionOperation.h └── AFURLConnectionOperation.m ├── README.md └── CHANGES /Example/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Icon.png -------------------------------------------------------------------------------- /Example/Default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Default.png -------------------------------------------------------------------------------- /Example/Icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Icon@2x.png -------------------------------------------------------------------------------- /Example/Default@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Default@2x.png -------------------------------------------------------------------------------- /Example/Default-568h@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Default-568h@2x.png -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Images/profile-image-placeholder.png -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wordpress-mobile/AFNetworking/wordpress-ios/Example/Images/profile-image-placeholder@2x.png -------------------------------------------------------------------------------- /Example/AFNetworking Mac Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Example/AFNetworking iOS Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /AFNetworking.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Example/AFNetworking Example.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.network.client 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Example/Prefix.pch: -------------------------------------------------------------------------------- 1 | #import 2 | 3 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 4 | #ifndef __IPHONE_3_0 5 | #warning "This project uses features only available in iPhone SDK 3.0 and later." 6 | #endif 7 | 8 | #ifdef __OBJC__ 9 | #import 10 | #import 11 | #import 12 | #import 13 | #endif 14 | #else 15 | #ifdef __OBJC__ 16 | #import 17 | #import 18 | #import 19 | #endif 20 | #endif -------------------------------------------------------------------------------- /AFNetworking.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = 'AFNetworking' 3 | s.version = '1.0' 4 | s.license = 'MIT' 5 | s.summary = 'A delightful iOS and OS X networking framework.' 6 | s.homepage = 'https://github.com/AFNetworking/AFNetworking' 7 | s.authors = { 'Mattt Thompson' => 'm@mattt.me', 'Scott Raymond' => 'sco@gowalla.com' } 8 | s.source = { :git => 'https://github.com/AFNetworking/AFNetworking.git', :tag => '1.0' } 9 | s.source_files = 'AFNetworking' 10 | s.requires_arc = true 11 | 12 | s.ios.deployment_target = '5.0' 13 | s.ios.frameworks = 'MobileCoreServices', 'SystemConfiguration' 14 | 15 | s.osx.deployment_target = '10.7' 16 | s.osx.frameworks = 'CoreServices', 'SystemConfiguration' 17 | 18 | s.prefix_header_contents = <<-EOS 19 | #import 20 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 21 | #import 22 | #import 23 | #else 24 | #import 25 | #import 26 | #endif 27 | EOS 28 | end 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011 Gowalla (http://gowalla.com/) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /Example/Mac-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | com.alamofire.${PRODUCT_NAME:rfc1034identifier} 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | ${PRODUCT_NAME} 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1 25 | LSMinimumSystemVersion 26 | ${MACOSX_DEPLOYMENT_TARGET} 27 | NSHumanReadableCopyright 28 | Copyright © 2012年 Mattt Thompson. All rights reserved. 29 | NSMainNibFile 30 | MainMenu 31 | NSPrincipalClass 32 | NSApplication 33 | 34 | 35 | -------------------------------------------------------------------------------- /Example/Classes/Controllers/GlobalTimelineViewController.h: -------------------------------------------------------------------------------- 1 | // GlobalTimelineViewController.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @interface GlobalTimelineViewController : UITableViewController 26 | 27 | @end 28 | -------------------------------------------------------------------------------- /Example/Classes/AFAppDotNetAPIClient.h: -------------------------------------------------------------------------------- 1 | // AFAppDotNetAPIClient.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPClient.h" 25 | 26 | @interface AFAppDotNetAPIClient : AFHTTPClient 27 | 28 | + (AFAppDotNetAPIClient *)sharedClient; 29 | 30 | @end 31 | -------------------------------------------------------------------------------- /Example/Classes/Views/PostTableViewCell.h: -------------------------------------------------------------------------------- 1 | // TweetTableViewCell.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @class Post; 26 | 27 | @interface PostTableViewCell : UITableViewCell 28 | 29 | @property (nonatomic, strong) Post *post; 30 | 31 | + (CGFloat)heightForCellWithPost:(Post *)post; 32 | 33 | @end 34 | -------------------------------------------------------------------------------- /Example/Classes/Models/Post.h: -------------------------------------------------------------------------------- 1 | // Post.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | @class User; 26 | 27 | @interface Post : NSObject 28 | 29 | @property (readonly) NSUInteger postID; 30 | @property (readonly) NSString *text; 31 | 32 | @property (readonly) User *user; 33 | 34 | - (id)initWithAttributes:(NSDictionary *)attributes; 35 | 36 | + (void)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block; 37 | 38 | @end 39 | -------------------------------------------------------------------------------- /Example/main.m: -------------------------------------------------------------------------------- 1 | // main.m 2 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 23 | #import 24 | 25 | int main(int argc, char *argv[]) { 26 | @autoreleasepool { 27 | int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate"); 28 | return retVal; 29 | } 30 | } 31 | #else 32 | #import 33 | 34 | int main(int argc, char *argv[]) { 35 | return NSApplicationMain(argc, (const char **)argv); 36 | } 37 | #endif 38 | -------------------------------------------------------------------------------- /Example/iOS-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | AFNetworking 9 | CFBundleExecutable 10 | ${EXECUTABLE_NAME} 11 | CFBundleIconFile 12 | 13 | CFBundleIconFiles 14 | 15 | Icon.png 16 | Icon@2x.png 17 | 18 | CFBundleIcons 19 | 20 | CFBundlePrimaryIcon 21 | 22 | CFBundleIconFiles 23 | 24 | Icon.png 25 | Icon@2x.png 26 | 27 | UIPrerenderedIcon 28 | 29 | 30 | 31 | CFBundleIdentifier 32 | com.alamofire.${PRODUCT_NAME:rfc1034identifier} 33 | CFBundleInfoDictionaryVersion 34 | 6.0 35 | CFBundleName 36 | ${PRODUCT_NAME} 37 | CFBundlePackageType 38 | APPL 39 | CFBundleShortVersionString 40 | 1.0 41 | CFBundleSignature 42 | ???? 43 | CFBundleVersion 44 | 1.0.0 45 | LSRequiresIPhoneOS 46 | 47 | UIPrerenderedIcon 48 | 49 | UIStatusBarHidden 50 | 51 | UISupportedInterfaceOrientations 52 | 53 | UIInterfaceOrientationPortrait 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Example/Classes/Models/User.h: -------------------------------------------------------------------------------- 1 | // User.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | extern NSString * const kUserProfileImageDidLoadNotification; 26 | 27 | @interface User : NSObject 28 | 29 | @property (readonly) NSUInteger userID; 30 | @property (readonly) NSString *username; 31 | @property (unsafe_unretained, readonly) NSURL *avatarImageURL; 32 | 33 | - (id)initWithAttributes:(NSDictionary *)attributes; 34 | 35 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 36 | @property (nonatomic, strong) NSImage *profileImage; 37 | #endif 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | #ifndef _AFNETWORKING_ 27 | #define _AFNETWORKING_ 28 | 29 | #import "AFURLConnectionOperation.h" 30 | 31 | #import "AFHTTPRequestOperation.h" 32 | #import "AFJSONRequestOperation.h" 33 | #import "AFXMLRequestOperation.h" 34 | #import "AFPropertyListRequestOperation.h" 35 | #import "AFHTTPClient.h" 36 | 37 | #import "AFImageRequestOperation.h" 38 | 39 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 40 | #import "AFNetworkActivityIndicatorManager.h" 41 | #import "UIImageView+AFNetworking.h" 42 | #endif 43 | 44 | #endif /* _AFNETWORKING_ */ 45 | -------------------------------------------------------------------------------- /Example/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // AppDelegate.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 26 | 27 | #import 28 | 29 | @interface AppDelegate : NSObject { 30 | 31 | } 32 | 33 | @property (nonatomic, strong) UIWindow *window; 34 | @property (nonatomic, strong) UINavigationController *navigationController; 35 | 36 | @end 37 | 38 | #else 39 | 40 | #import 41 | 42 | @interface AppDelegate : NSObject 43 | 44 | @property (strong) IBOutlet NSWindow *window; 45 | @property (strong) IBOutlet NSTableView *tableView; 46 | @property (strong) IBOutlet NSArrayController *postsArrayController; 47 | 48 | @end 49 | 50 | #endif 51 | -------------------------------------------------------------------------------- /Example/Classes/AFAppDotNetAPIClient.m: -------------------------------------------------------------------------------- 1 | // AFAppDotNetAPIClient.h 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFAppDotNetAPIClient.h" 24 | 25 | #import "AFJSONRequestOperation.h" 26 | 27 | static NSString * const kAFAppDotNetAPIBaseURLString = @"https://alpha-api.app.net/"; 28 | 29 | @implementation AFAppDotNetAPIClient 30 | 31 | + (AFAppDotNetAPIClient *)sharedClient { 32 | static AFAppDotNetAPIClient *_sharedClient = nil; 33 | static dispatch_once_t onceToken; 34 | dispatch_once(&onceToken, ^{ 35 | _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kAFAppDotNetAPIBaseURLString]]; 36 | }); 37 | 38 | return _sharedClient; 39 | } 40 | 41 | - (id)initWithBaseURL:(NSURL *)url { 42 | self = [super initWithBaseURL:url]; 43 | if (!self) { 44 | return nil; 45 | } 46 | 47 | [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; 48 | 49 | // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 50 | [self setDefaultHeader:@"Accept" value:@"application/json"]; 51 | 52 | return self; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /Example/Classes/Models/Post.m: -------------------------------------------------------------------------------- 1 | // Post.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "Post.h" 24 | #import "User.h" 25 | 26 | #import "AFAppDotNetAPIClient.h" 27 | 28 | @implementation Post 29 | @synthesize postID = _postID; 30 | @synthesize text = _text; 31 | @synthesize user = _user; 32 | 33 | - (id)initWithAttributes:(NSDictionary *)attributes { 34 | self = [super init]; 35 | if (!self) { 36 | return nil; 37 | } 38 | 39 | _postID = [[attributes valueForKeyPath:@"id"] integerValue]; 40 | _text = [attributes valueForKeyPath:@"text"]; 41 | 42 | _user = [[User alloc] initWithAttributes:[attributes valueForKeyPath:@"user"]]; 43 | 44 | return self; 45 | } 46 | 47 | #pragma mark - 48 | 49 | + (void)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block { 50 | [[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) { 51 | NSMutableArray *mutablePosts = [NSMutableArray arrayWithCapacity:[JSON count]]; 52 | for (NSDictionary *attributes in JSON) { 53 | Post *post = [[Post alloc] initWithAttributes:attributes]; 54 | [mutablePosts addObject:post]; 55 | } 56 | 57 | if (block) { 58 | block([NSArray arrayWithArray:mutablePosts], nil); 59 | } 60 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 61 | if (block) { 62 | block([NSArray array], error); 63 | } 64 | }]; 65 | } 66 | 67 | @end 68 | -------------------------------------------------------------------------------- /Example/Classes/Views/PostTableViewCell.m: -------------------------------------------------------------------------------- 1 | // TweetTableViewCell.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "PostTableViewCell.h" 24 | 25 | #import "Post.h" 26 | #import "User.h" 27 | 28 | #import "UIImageView+AFNetworking.h" 29 | 30 | @implementation PostTableViewCell { 31 | @private 32 | __strong Post *_post; 33 | } 34 | 35 | @synthesize post = _post; 36 | 37 | - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 38 | self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 39 | if (!self) { 40 | return nil; 41 | } 42 | 43 | self.textLabel.adjustsFontSizeToFitWidth = YES; 44 | self.textLabel.textColor = [UIColor darkGrayColor]; 45 | self.detailTextLabel.font = [UIFont systemFontOfSize:12.0f]; 46 | self.detailTextLabel.numberOfLines = 0; 47 | self.selectionStyle = UITableViewCellSelectionStyleGray; 48 | 49 | return self; 50 | } 51 | 52 | - (void)setPost:(Post *)post { 53 | _post = post; 54 | 55 | self.textLabel.text = _post.user.username; 56 | self.detailTextLabel.text = _post.text; 57 | [self.imageView setImageWithURL:_post.user.avatarImageURL placeholderImage:[UIImage imageNamed:@"profile-image-placeholder"]]; 58 | 59 | [self setNeedsLayout]; 60 | } 61 | 62 | + (CGFloat)heightForCellWithPost:(Post *)post { 63 | CGSize sizeToFit = [post.text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:CGSizeMake(220.0f, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; 64 | 65 | return fmaxf(70.0f, sizeToFit.height + 45.0f); 66 | } 67 | 68 | #pragma mark - UIView 69 | 70 | - (void)layoutSubviews { 71 | [super layoutSubviews]; 72 | 73 | self.imageView.frame = CGRectMake(10.0f, 10.0f, 50.0f, 50.0f); 74 | self.textLabel.frame = CGRectMake(70.0f, 10.0f, 240.0f, 20.0f); 75 | 76 | CGRect detailTextLabelFrame = CGRectOffset(self.textLabel.frame, 0.0f, 25.0f); 77 | detailTextLabelFrame.size.height = [[self class] heightForCellWithPost:_post] - 45.0f; 78 | self.detailTextLabel.frame = detailTextLabelFrame; 79 | } 80 | 81 | @end 82 | -------------------------------------------------------------------------------- /AFNetworking/AFPropertyListRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFPropertyListRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPRequestOperation.h" 25 | 26 | /** 27 | `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data. 28 | 29 | ## Acceptable Content Types 30 | 31 | By default, `AFPropertyListRequestOperation` accepts the following MIME types: 32 | 33 | - `application/x-plist` 34 | */ 35 | @interface AFPropertyListRequestOperation : AFHTTPRequestOperation 36 | 37 | ///---------------------------- 38 | /// @name Getting Response Data 39 | ///---------------------------- 40 | 41 | /** 42 | An object deserialized from a plist constructed using the response data. 43 | */ 44 | @property (readonly, nonatomic) id responsePropertyList; 45 | 46 | ///-------------------------------------- 47 | /// @name Managing Property List Behavior 48 | ///-------------------------------------- 49 | 50 | /** 51 | One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`. 52 | */ 53 | @property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions; 54 | 55 | /** 56 | Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks. 57 | 58 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 59 | @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. 60 | @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. 61 | 62 | @return A new property list request operation 63 | */ 64 | + (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest 65 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success 66 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure; 67 | 68 | @end 69 | -------------------------------------------------------------------------------- /Example/Classes/Models/User.m: -------------------------------------------------------------------------------- 1 | // User.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "User.h" 24 | #import "AFImageRequestOperation.h" 25 | 26 | NSString * const kUserProfileImageDidLoadNotification = @"com.alamofire.user.profile-image.loaded"; 27 | 28 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 29 | @interface User () 30 | + (NSOperationQueue *)sharedProfileImageRequestOperationQueue; 31 | @end 32 | #endif 33 | 34 | @implementation User { 35 | @private 36 | NSString *_avatarImageURLString; 37 | AFImageRequestOperation *_avatarImageRequestOperation; 38 | } 39 | 40 | @synthesize userID = _userID; 41 | @synthesize username = _username; 42 | 43 | - (id)initWithAttributes:(NSDictionary *)attributes { 44 | self = [super init]; 45 | if (!self) { 46 | return nil; 47 | } 48 | 49 | _userID = [[attributes valueForKeyPath:@"id"] integerValue]; 50 | _username = [attributes valueForKeyPath:@"username"]; 51 | _avatarImageURLString = [attributes valueForKeyPath:@"avatar_image.url"]; 52 | 53 | return self; 54 | } 55 | 56 | - (NSURL *)avatarImageURL { 57 | return [NSURL URLWithString:_avatarImageURLString]; 58 | } 59 | 60 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 61 | 62 | @synthesize profileImage = _profileImage; 63 | 64 | + (NSOperationQueue *)sharedProfileImageRequestOperationQueue { 65 | static NSOperationQueue *_sharedProfileImageRequestOperationQueue = nil; 66 | static dispatch_once_t onceToken; 67 | dispatch_once(&onceToken, ^{ 68 | _sharedProfileImageRequestOperationQueue = [[NSOperationQueue alloc] init]; 69 | [_sharedProfileImageRequestOperationQueue setMaxConcurrentOperationCount:8]; 70 | }); 71 | 72 | return _sharedProfileImageRequestOperationQueue; 73 | } 74 | 75 | - (NSImage *)profileImage { 76 | if (!_profileImage && !_avatarImageRequestOperation) { 77 | _avatarImageRequestOperation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:self.avatarImageURL] success:^(NSImage *image) { 78 | self.profileImage = image; 79 | 80 | _avatarImageRequestOperation = nil; 81 | 82 | [[NSNotificationCenter defaultCenter] postNotificationName:kUserProfileImageDidLoadNotification object:self userInfo:nil]; 83 | }]; 84 | 85 | [_avatarImageRequestOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) { 86 | return [[NSCachedURLResponse alloc] initWithResponse:cachedResponse.response data:cachedResponse.data userInfo:cachedResponse.userInfo storagePolicy:NSURLCacheStorageAllowed]; 87 | }]; 88 | 89 | [[[self class] sharedProfileImageRequestOperationQueue] addOperation:_avatarImageRequestOperation]; 90 | } 91 | 92 | return _profileImage; 93 | } 94 | 95 | #endif 96 | 97 | @end 98 | -------------------------------------------------------------------------------- /AFNetworking/AFJSONRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPRequestOperation.h" 25 | 26 | /** 27 | `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data. 28 | 29 | ## Acceptable Content Types 30 | 31 | By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 32 | 33 | - `application/json` 34 | - `text/json` 35 | 36 | @warning JSON parsing will automatically use JSONKit, SBJSON, YAJL, or NextiveJSON, if provided. Otherwise, the built-in `NSJSONSerialization` class is used, if available (iOS 5.0 and Mac OS 10.7). If the build target does not either support `NSJSONSerialization` or include a third-party JSON library, a runtime exception will be thrown when attempting to parse a JSON request. 37 | */ 38 | @interface AFJSONRequestOperation : AFHTTPRequestOperation 39 | 40 | ///---------------------------- 41 | /// @name Getting Response Data 42 | ///---------------------------- 43 | 44 | /** 45 | 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. 46 | */ 47 | @property (readonly, nonatomic, strong) id responseJSON; 48 | 49 | ///---------------------------------- 50 | /// @name Creating Request Operations 51 | ///---------------------------------- 52 | 53 | /** 54 | Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. 55 | 56 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 57 | @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. 58 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response 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. 59 | 60 | @return A new JSON request operation 61 | */ 62 | + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 63 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 64 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure; 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /AFNetworking/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #import 26 | 27 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 28 | #import 29 | 30 | /** 31 | `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. 32 | 33 | You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: 34 | 35 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 36 | 37 | By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. 38 | 39 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: 40 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 41 | */ 42 | @interface AFNetworkActivityIndicatorManager : NSObject 43 | 44 | /** 45 | A Boolean value indicating whether the manager is enabled. 46 | 47 | @discussion If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. 48 | */ 49 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled; 50 | 51 | /** 52 | A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. 53 | */ 54 | @property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; 55 | 56 | /** 57 | Returns the shared network activity indicator manager object for the system. 58 | 59 | @return The systemwide network activity indicator manager. 60 | */ 61 | + (AFNetworkActivityIndicatorManager *)sharedManager; 62 | 63 | /** 64 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. 65 | */ 66 | - (void)incrementActivityCount; 67 | 68 | /** 69 | Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator. 70 | */ 71 | - (void)decrementActivityCount; 72 | 73 | @end 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /Example/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // AppDelegate.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AppDelegate.h" 24 | 25 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 26 | 27 | #import "GlobalTimelineViewController.h" 28 | 29 | #import "AFNetworkActivityIndicatorManager.h" 30 | 31 | @implementation AppDelegate 32 | @synthesize window = _window; 33 | @synthesize navigationController = _navigationController; 34 | 35 | - (BOOL)application:(UIApplication *)application 36 | didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 37 | { 38 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 39 | [NSURLCache setSharedURLCache:URLCache]; 40 | 41 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 42 | 43 | UITableViewController *viewController = [[GlobalTimelineViewController alloc] initWithStyle:UITableViewStylePlain]; 44 | self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; 45 | self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor]; 46 | 47 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 48 | self.window.backgroundColor = [UIColor whiteColor]; 49 | self.window.rootViewController = self.navigationController; 50 | [self.window makeKeyAndVisible]; 51 | 52 | return YES; 53 | } 54 | 55 | @end 56 | 57 | #else 58 | 59 | #import "Post.h" 60 | #import "User.h" 61 | 62 | @implementation AppDelegate 63 | 64 | @synthesize window = _window; 65 | @synthesize tableView = _tableView; 66 | @synthesize postsArrayController = _postsArrayController; 67 | 68 | - (void)applicationDidFinishLaunching:(NSNotification *)notification { 69 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 70 | [NSURLCache setSharedURLCache:URLCache]; 71 | 72 | [self.window makeKeyAndOrderFront:self]; 73 | 74 | [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 75 | if (error) { 76 | [[NSAlert alertWithMessageText:NSLocalizedString(@"Error", nil) defaultButton:NSLocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@",[error localizedDescription]] runModal]; 77 | } 78 | 79 | self.postsArrayController.content = posts; 80 | }]; 81 | 82 | [[NSNotificationCenter defaultCenter] addObserverForName:kUserProfileImageDidLoadNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { 83 | [self.tableView reloadData]; 84 | }]; 85 | } 86 | 87 | - (BOOL)applicationShouldHandleReopen:(NSApplication *)application 88 | hasVisibleWindows:(BOOL)flag 89 | { 90 | [self.window makeKeyAndOrderFront:self]; 91 | 92 | return YES; 93 | } 94 | 95 | @end 96 | 97 | #endif -------------------------------------------------------------------------------- /Example/Classes/Controllers/GlobalTimelineViewController.m: -------------------------------------------------------------------------------- 1 | // GlobalTimelineViewController.m 2 | // 3 | // Copyright (c) 2012 Mattt Thompson (http://mattt.me/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "GlobalTimelineViewController.h" 24 | 25 | #import "Post.h" 26 | 27 | #import "PostTableViewCell.h" 28 | 29 | @interface GlobalTimelineViewController () 30 | - (void)reload:(id)sender; 31 | @end 32 | 33 | @implementation GlobalTimelineViewController { 34 | @private 35 | NSArray *_posts; 36 | 37 | __strong UIActivityIndicatorView *_activityIndicatorView; 38 | } 39 | 40 | - (void)reload:(id)sender { 41 | [_activityIndicatorView startAnimating]; 42 | self.navigationItem.rightBarButtonItem.enabled = NO; 43 | 44 | [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 45 | if (error) { 46 | [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil) message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil), nil] show]; 47 | } else { 48 | _posts = posts; 49 | [self.tableView reloadData]; 50 | } 51 | 52 | [_activityIndicatorView stopAnimating]; 53 | self.navigationItem.rightBarButtonItem.enabled = YES; 54 | }]; 55 | } 56 | 57 | #pragma mark - UIViewController 58 | 59 | - (void)loadView { 60 | [super loadView]; 61 | 62 | _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]; 63 | _activityIndicatorView.hidesWhenStopped = YES; 64 | } 65 | 66 | - (void)viewDidLoad { 67 | [super viewDidLoad]; 68 | 69 | self.title = NSLocalizedString(@"AFNetworking", nil); 70 | 71 | self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_activityIndicatorView]; 72 | self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)]; 73 | 74 | self.tableView.rowHeight = 70.0f; 75 | 76 | [self reload:nil]; 77 | } 78 | 79 | - (void)viewDidUnload { 80 | _activityIndicatorView = nil; 81 | 82 | [super viewDidUnload]; 83 | } 84 | 85 | #pragma mark - UITableViewDataSource 86 | 87 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 88 | return [_posts count]; 89 | } 90 | 91 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 92 | static NSString *CellIdentifier = @"Cell"; 93 | 94 | PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 95 | if (!cell) { 96 | cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 97 | } 98 | 99 | cell.post = [_posts objectAtIndex:indexPath.row]; 100 | 101 | return cell; 102 | } 103 | 104 | #pragma mark - UITableViewDelegate 105 | 106 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 107 | return [PostTableViewCell heightForCellWithPost:[_posts objectAtIndex:indexPath.row]]; 108 | } 109 | 110 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 111 | [tableView deselectRowAtIndexPath:indexPath animated:YES]; 112 | } 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /AFNetworking/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFImageRequestOperation.h" 25 | 26 | #import 27 | 28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 29 | #import 30 | 31 | /** 32 | 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. 33 | */ 34 | @interface UIImageView (AFNetworking) 35 | 36 | /** 37 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 38 | 39 | @discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 40 | 41 | @param url The URL used for the image request. 42 | */ 43 | - (void)setImageWithURL:(NSURL *)url; 44 | 45 | /** 46 | Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 47 | 48 | @param url The URL used for the image request. 49 | @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. 50 | 51 | @discussion By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 52 | */ 53 | - (void)setImageWithURL:(NSURL *)url 54 | placeholderImage:(UIImage *)placeholderImage; 55 | 56 | /** 57 | Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 58 | 59 | @param urlRequest The URL request used for the image request. 60 | @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. 61 | @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`. 62 | @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. 63 | */ 64 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 65 | placeholderImage:(UIImage *)placeholderImage 66 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 67 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 68 | 69 | /** 70 | Cancels any executing image request operation for the receiver, if one exists. 71 | */ 72 | - (void)cancelImageRequestOperation; 73 | 74 | @end 75 | 76 | #endif 77 | -------------------------------------------------------------------------------- /AFNetworking/AFXMLRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFXMLRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPRequestOperation.h" 25 | 26 | #import 27 | 28 | /** 29 | `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data. 30 | 31 | ## Acceptable Content Types 32 | 33 | By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 34 | 35 | - `application/xml` 36 | - `text/xml` 37 | 38 | ## Use With AFHTTPClient 39 | 40 | When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback. 41 | */ 42 | @interface AFXMLRequestOperation : AFHTTPRequestOperation 43 | 44 | ///---------------------------- 45 | /// @name Getting Response Data 46 | ///---------------------------- 47 | 48 | /** 49 | An `NSXMLParser` object constructed from the response data. 50 | */ 51 | @property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser; 52 | 53 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 54 | /** 55 | 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. 56 | */ 57 | @property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument; 58 | #endif 59 | 60 | /** 61 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. 62 | 63 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 64 | @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. 65 | @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. 66 | 67 | @return A new XML request operation 68 | */ 69 | + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 70 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 71 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParse))failure; 72 | 73 | 74 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 75 | /** 76 | Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. 77 | 78 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 79 | @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. 80 | @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response 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. 81 | 82 | @return A new XML request operation 83 | */ 84 | + (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest 85 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success 86 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure; 87 | #endif 88 | 89 | @end 90 | -------------------------------------------------------------------------------- /AFNetworking/AFNetworkActivityIndicatorManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFNetworkActivityIndicatorManager.h" 24 | 25 | #import "AFHTTPRequestOperation.h" 26 | 27 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 28 | static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; 29 | 30 | @interface AFNetworkActivityIndicatorManager () 31 | @property (readwrite, assign) NSInteger activityCount; 32 | @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; 33 | @property (readonly, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 34 | 35 | - (void)updateNetworkActivityIndicatorVisibility; 36 | - (void)updateNetworkActivityIndicatorVisibilityDelayed; 37 | @end 38 | 39 | @implementation AFNetworkActivityIndicatorManager 40 | @synthesize activityCount = _activityCount; 41 | @synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; 42 | @synthesize enabled = _enabled; 43 | @dynamic networkActivityIndicatorVisible; 44 | 45 | + (AFNetworkActivityIndicatorManager *)sharedManager { 46 | static AFNetworkActivityIndicatorManager *_sharedManager = nil; 47 | static dispatch_once_t oncePredicate; 48 | dispatch_once(&oncePredicate, ^{ 49 | _sharedManager = [[self alloc] init]; 50 | }); 51 | 52 | return _sharedManager; 53 | } 54 | 55 | + (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { 56 | return [NSSet setWithObject:@"activityCount"]; 57 | } 58 | 59 | - (id)init { 60 | self = [super init]; 61 | if (!self) { 62 | return nil; 63 | } 64 | 65 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incrementActivityCount) name:AFNetworkingOperationDidStartNotification object:nil]; 66 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(decrementActivityCount) name:AFNetworkingOperationDidFinishNotification object:nil]; 67 | 68 | return self; 69 | } 70 | 71 | - (void)dealloc { 72 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 73 | 74 | [_activityIndicatorVisibilityTimer invalidate]; 75 | 76 | } 77 | 78 | - (void)updateNetworkActivityIndicatorVisibilityDelayed { 79 | if (self.enabled) { 80 | // Delay hiding of activity indicator for a short interval, to avoid flickering 81 | if (![self isNetworkActivityIndicatorVisible]) { 82 | [self.activityIndicatorVisibilityTimer invalidate]; 83 | self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; 84 | [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; 85 | } else { 86 | [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; 87 | } 88 | } 89 | } 90 | 91 | - (BOOL)isNetworkActivityIndicatorVisible { 92 | return _activityCount > 0; 93 | } 94 | 95 | - (void)updateNetworkActivityIndicatorVisibility { 96 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; 97 | } 98 | 99 | // Not exposed, but used if activityCount is set via KVC. 100 | - (NSInteger)activityCount { 101 | return _activityCount; 102 | } 103 | 104 | - (void)setActivityCount:(NSInteger)activityCount { 105 | @synchronized(self) { 106 | _activityCount = activityCount; 107 | } 108 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 109 | } 110 | 111 | - (void)incrementActivityCount { 112 | [self willChangeValueForKey:@"activityCount"]; 113 | @synchronized(self) { 114 | _activityCount++; 115 | } 116 | [self didChangeValueForKey:@"activityCount"]; 117 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 118 | } 119 | 120 | - (void)decrementActivityCount { 121 | [self willChangeValueForKey:@"activityCount"]; 122 | @synchronized(self) { 123 | _activityCount = MAX(_activityCount - 1, 0); 124 | } 125 | [self didChangeValueForKey:@"activityCount"]; 126 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 127 | } 128 | 129 | @end 130 | 131 | #endif 132 | -------------------------------------------------------------------------------- /AFNetworking/AFJSONRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFJSONRequestOperation.h" 24 | 25 | static dispatch_queue_t af_json_request_operation_processing_queue; 26 | static dispatch_queue_t json_request_operation_processing_queue() { 27 | if (af_json_request_operation_processing_queue == NULL) { 28 | af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", 0); 29 | } 30 | 31 | return af_json_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFJSONRequestOperation () 35 | @property (readwrite, nonatomic, strong) id responseJSON; 36 | @property (readwrite, nonatomic, strong) NSError *JSONError; 37 | @end 38 | 39 | @implementation AFJSONRequestOperation 40 | @synthesize responseJSON = _responseJSON; 41 | @synthesize JSONError = _JSONError; 42 | 43 | + (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 44 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 45 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure 46 | { 47 | AFJSONRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 48 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 49 | if (success) { 50 | success(operation.request, operation.response, responseObject); 51 | } 52 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 53 | if (failure) { 54 | failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]); 55 | } 56 | }]; 57 | 58 | return requestOperation; 59 | } 60 | 61 | 62 | - (id)responseJSON { 63 | if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) { 64 | NSError *error = nil; 65 | 66 | if ([self.responseData length] == 0) { 67 | self.responseJSON = nil; 68 | } else { 69 | self.responseJSON = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error]; 70 | } 71 | 72 | self.JSONError = error; 73 | } 74 | 75 | return _responseJSON; 76 | } 77 | 78 | - (NSError *)error { 79 | if (_JSONError) { 80 | return _JSONError; 81 | } else { 82 | return [super error]; 83 | } 84 | } 85 | 86 | #pragma mark - AFHTTPRequestOperation 87 | 88 | + (NSSet *)acceptableContentTypes { 89 | return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; 90 | } 91 | 92 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 93 | return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request]; 94 | } 95 | 96 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 97 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 98 | { 99 | #pragma clang diagnostic push 100 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 101 | self.completionBlock = ^ { 102 | if ([self isCancelled]) { 103 | return; 104 | } 105 | 106 | if (self.error) { 107 | if (failure) { 108 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 109 | failure(self, self.error); 110 | }); 111 | } 112 | } else { 113 | dispatch_async(json_request_operation_processing_queue(), ^{ 114 | id JSON = self.responseJSON; 115 | 116 | if (self.JSONError) { 117 | if (failure) { 118 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 119 | failure(self, self.error); 120 | }); 121 | } 122 | } else { 123 | if (success) { 124 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 125 | success(self, JSON); 126 | }); 127 | } 128 | } 129 | }); 130 | } 131 | }; 132 | #pragma clang diagnostic pop 133 | } 134 | 135 | @end 136 | -------------------------------------------------------------------------------- /AFNetworking/AFImageRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFImageRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFHTTPRequestOperation.h" 25 | 26 | #import 27 | 28 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 29 | #import 30 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 31 | #import 32 | #endif 33 | 34 | /** 35 | `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading an processing images. 36 | 37 | ## Acceptable Content Types 38 | 39 | By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 40 | 41 | - `image/tiff` 42 | - `image/jpeg` 43 | - `image/gif` 44 | - `image/png` 45 | - `image/ico` 46 | - `image/x-icon` 47 | - `image/bmp` 48 | - `image/x-bmp` 49 | - `image/x-xbitmap` 50 | - `image/x-win-bitmap` 51 | */ 52 | @interface AFImageRequestOperation : AFHTTPRequestOperation 53 | 54 | /** 55 | An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error. 56 | */ 57 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 58 | @property (readonly, nonatomic, strong) UIImage *responseImage; 59 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 60 | @property (readonly, nonatomic, strong) NSImage *responseImage; 61 | #endif 62 | 63 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 64 | /** 65 | The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. 66 | */ 67 | @property (nonatomic, assign) CGFloat imageScale; 68 | #endif 69 | 70 | /** 71 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 72 | 73 | @param urlRequest The request object to be loaded asynchronously during execution of the operation. 74 | @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. 75 | 76 | @return A new image request operation 77 | */ 78 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 79 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 80 | success:(void (^)(UIImage *image))success; 81 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 82 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 83 | success:(void (^)(NSImage *image))success; 84 | #endif 85 | 86 | /** 87 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 88 | 89 | @param urlRequest The request object to be loaded asynchronously during execution of the operation. 90 | @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image. 91 | @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 three arguments: the request object of the operation, the response for the request, and the image created from the response data. 92 | @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation. 93 | 94 | @return A new image request operation 95 | */ 96 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 97 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 98 | imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock 99 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 100 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 101 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 102 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 103 | imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock 104 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 105 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 106 | #endif 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /AFNetworking/AFPropertyListRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFPropertyListRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFPropertyListRequestOperation.h" 24 | 25 | static dispatch_queue_t af_property_list_request_operation_processing_queue; 26 | static dispatch_queue_t property_list_request_operation_processing_queue() { 27 | if (af_property_list_request_operation_processing_queue == NULL) { 28 | af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", 0); 29 | } 30 | 31 | return af_property_list_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFPropertyListRequestOperation () 35 | @property (readwrite, nonatomic) id responsePropertyList; 36 | @property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; 37 | @property (readwrite, nonatomic) NSError *propertyListError; 38 | @end 39 | 40 | @implementation AFPropertyListRequestOperation 41 | @synthesize responsePropertyList = _responsePropertyList; 42 | @synthesize propertyListReadOptions = _propertyListReadOptions; 43 | @synthesize propertyListFormat = _propertyListFormat; 44 | @synthesize propertyListError = _propertyListError; 45 | 46 | + (AFPropertyListRequestOperation *)propertyListRequestOperationWithRequest:(NSURLRequest *)request 47 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success 48 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure 49 | { 50 | AFPropertyListRequestOperation *requestOperation = [[self alloc] initWithRequest:request]; 51 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 52 | if (success) { 53 | success(operation.request, operation.response, responseObject); 54 | } 55 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 56 | if (failure) { 57 | failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]); 58 | } 59 | }]; 60 | 61 | return requestOperation; 62 | } 63 | 64 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 65 | self = [super initWithRequest:urlRequest]; 66 | if (!self) { 67 | return nil; 68 | } 69 | 70 | self.propertyListReadOptions = NSPropertyListImmutable; 71 | 72 | return self; 73 | } 74 | 75 | 76 | - (id)responsePropertyList { 77 | if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) { 78 | NSPropertyListFormat format; 79 | NSError *error = nil; 80 | self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; 81 | self.propertyListFormat = format; 82 | self.propertyListError = error; 83 | } 84 | 85 | return _responsePropertyList; 86 | } 87 | 88 | - (NSError *)error { 89 | if (_propertyListError) { 90 | return _propertyListError; 91 | } else { 92 | return [super error]; 93 | } 94 | } 95 | 96 | #pragma mark - AFHTTPRequestOperation 97 | 98 | + (NSSet *)acceptableContentTypes { 99 | return [NSSet setWithObjects:@"application/x-plist", nil]; 100 | } 101 | 102 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 103 | return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request]; 104 | } 105 | 106 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 107 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 108 | { 109 | #pragma clang diagnostic push 110 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 111 | self.completionBlock = ^ { 112 | if ([self isCancelled]) { 113 | return; 114 | } 115 | 116 | if (self.error) { 117 | if (failure) { 118 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 119 | failure(self, self.error); 120 | }); 121 | } 122 | } else { 123 | dispatch_async(property_list_request_operation_processing_queue(), ^(void) { 124 | id propertyList = self.responsePropertyList; 125 | 126 | if (self.propertyListError) { 127 | if (failure) { 128 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 129 | failure(self, self.error); 130 | }); 131 | } 132 | } else { 133 | if (success) { 134 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 135 | success(self, propertyList); 136 | }); 137 | } 138 | } 139 | }); 140 | } 141 | }; 142 | #pragma clang diagnostic pop 143 | } 144 | 145 | @end 146 | -------------------------------------------------------------------------------- /AFNetworking/AFHTTPRequestOperation.h: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import "AFURLConnectionOperation.h" 25 | 26 | /** 27 | `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. 28 | */ 29 | @interface AFHTTPRequestOperation : AFURLConnectionOperation 30 | 31 | ///---------------------------------------------- 32 | /// @name Getting HTTP URL Connection Information 33 | ///---------------------------------------------- 34 | 35 | /** 36 | The last HTTP response received by the operation's connection. 37 | */ 38 | @property (readonly, nonatomic, strong) NSHTTPURLResponse *response; 39 | 40 | ///---------------------------------------------------------- 41 | /// @name Managing And Checking For Acceptable HTTP Responses 42 | ///---------------------------------------------------------- 43 | 44 | /** 45 | 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`. 46 | */ 47 | @property (readonly) BOOL hasAcceptableStatusCode; 48 | 49 | /** 50 | 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`. 51 | */ 52 | @property (readonly) BOOL hasAcceptableContentType; 53 | 54 | /** 55 | The callback dispatch queue on success. If `NULL` (default), the main queue is used. 56 | */ 57 | @property (nonatomic, assign) dispatch_queue_t successCallbackQueue; 58 | 59 | /** 60 | The callback dispatch queue on failure. If `NULL` (default), the main queue is used. 61 | */ 62 | @property (nonatomic, assign) dispatch_queue_t failureCallbackQueue; 63 | 64 | ///------------------------------------------------------------ 65 | /// @name Managing Acceptable HTTP Status Codes & Content Types 66 | ///------------------------------------------------------------ 67 | 68 | /** 69 | 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 70 | 71 | By default, this is the range 200 to 299, inclusive. 72 | */ 73 | + (NSIndexSet *)acceptableStatusCodes; 74 | 75 | /** 76 | Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants. 77 | 78 | @param statusCodes The status codes to be added to the set of acceptable HTTP status codes 79 | */ 80 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes; 81 | 82 | /** 83 | 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 84 | 85 | By default, this is `nil`. 86 | */ 87 | + (NSSet *)acceptableContentTypes; 88 | 89 | /** 90 | Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants. 91 | 92 | @param contentTypes The content types to be added to the set of acceptable MIME types 93 | */ 94 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes; 95 | 96 | 97 | ///----------------------------------------------------- 98 | /// @name Determining Whether A Request Can Be Processed 99 | ///----------------------------------------------------- 100 | 101 | /** 102 | 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`. 103 | 104 | @param urlRequest The request that is determined to be supported or not supported for this class. 105 | */ 106 | + (BOOL)canProcessRequest:(NSURLRequest *)urlRequest; 107 | 108 | ///----------------------------------------------------------- 109 | /// @name Setting Completion Block Success / Failure Callbacks 110 | ///----------------------------------------------------------- 111 | 112 | /** 113 | Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. 114 | 115 | @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. 116 | @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. 117 | 118 | @discussion This method should be overridden in subclasses in order to specify the response object passed into the success block. 119 | */ 120 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 121 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 122 | 123 | @end 124 | 125 | ///---------------- 126 | /// @name Functions 127 | ///---------------- 128 | 129 | /** 130 | Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header. 131 | */ 132 | extern NSSet * AFContentTypesFromHTTPHeader(NSString *string); 133 | 134 | -------------------------------------------------------------------------------- /AFNetworking/UIImageView+AFNetworking.m: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | 26 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 27 | #import "UIImageView+AFNetworking.h" 28 | 29 | @interface AFImageCache : NSCache 30 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request; 31 | - (void)cacheImage:(UIImage *)image 32 | forRequest:(NSURLRequest *)request; 33 | @end 34 | 35 | #pragma mark - 36 | 37 | static char kAFImageRequestOperationObjectKey; 38 | 39 | @interface UIImageView (_AFNetworking) 40 | @property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; 41 | @end 42 | 43 | @implementation UIImageView (_AFNetworking) 44 | @dynamic af_imageRequestOperation; 45 | @end 46 | 47 | #pragma mark - 48 | 49 | @implementation UIImageView (AFNetworking) 50 | 51 | - (AFHTTPRequestOperation *)af_imageRequestOperation { 52 | return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); 53 | } 54 | 55 | - (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { 56 | objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 57 | } 58 | 59 | + (NSOperationQueue *)af_sharedImageRequestOperationQueue { 60 | static NSOperationQueue *_af_imageRequestOperationQueue = nil; 61 | 62 | static dispatch_once_t onceToken; 63 | dispatch_once(&onceToken, ^{ 64 | _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init]; 65 | [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; 66 | }); 67 | 68 | return _af_imageRequestOperationQueue; 69 | } 70 | 71 | + (AFImageCache *)af_sharedImageCache { 72 | static AFImageCache *_af_imageCache = nil; 73 | static dispatch_once_t oncePredicate; 74 | dispatch_once(&oncePredicate, ^{ 75 | _af_imageCache = [[AFImageCache alloc] init]; 76 | }); 77 | 78 | return _af_imageCache; 79 | } 80 | 81 | #pragma mark - 82 | 83 | - (void)setImageWithURL:(NSURL *)url { 84 | [self setImageWithURL:url placeholderImage:nil]; 85 | } 86 | 87 | - (void)setImageWithURL:(NSURL *)url 88 | placeholderImage:(UIImage *)placeholderImage 89 | { 90 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 91 | [request setHTTPShouldHandleCookies:NO]; 92 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 93 | 94 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 95 | } 96 | 97 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 98 | placeholderImage:(UIImage *)placeholderImage 99 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 100 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 101 | { 102 | [self cancelImageRequestOperation]; 103 | 104 | UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest]; 105 | if (cachedImage) { 106 | self.image = cachedImage; 107 | self.af_imageRequestOperation = nil; 108 | 109 | if (success) { 110 | success(nil, nil, cachedImage); 111 | } 112 | } else { 113 | self.image = placeholderImage; 114 | 115 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 116 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 117 | if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { 118 | self.image = responseObject; 119 | self.af_imageRequestOperation = nil; 120 | } 121 | 122 | if (success) { 123 | success(operation.request, operation.response, responseObject); 124 | } 125 | 126 | [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; 127 | 128 | 129 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 130 | if ([[urlRequest URL] isEqual:[[self.af_imageRequestOperation request] URL]]) { 131 | self.af_imageRequestOperation = nil; 132 | } 133 | 134 | if (failure) { 135 | failure(operation.request, operation.response, error); 136 | } 137 | 138 | }]; 139 | 140 | self.af_imageRequestOperation = requestOperation; 141 | 142 | [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; 143 | } 144 | } 145 | 146 | - (void)cancelImageRequestOperation { 147 | [self.af_imageRequestOperation cancel]; 148 | self.af_imageRequestOperation = nil; 149 | } 150 | 151 | @end 152 | 153 | #pragma mark - 154 | 155 | static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { 156 | return [[request URL] absoluteString]; 157 | } 158 | 159 | @implementation AFImageCache 160 | 161 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request { 162 | switch ([request cachePolicy]) { 163 | case NSURLRequestReloadIgnoringCacheData: 164 | case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: 165 | return nil; 166 | default: 167 | break; 168 | } 169 | 170 | return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; 171 | } 172 | 173 | - (void)cacheImage:(UIImage *)image 174 | forRequest:(NSURLRequest *)request 175 | { 176 | if (image && request) { 177 | [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; 178 | } 179 | } 180 | 181 | @end 182 | 183 | #endif 184 | -------------------------------------------------------------------------------- /AFNetworking/AFXMLRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFXMLRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFXMLRequestOperation.h" 24 | 25 | #include 26 | 27 | static dispatch_queue_t af_xml_request_operation_processing_queue; 28 | static dispatch_queue_t xml_request_operation_processing_queue() { 29 | if (af_xml_request_operation_processing_queue == NULL) { 30 | af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", 0); 31 | } 32 | 33 | return af_xml_request_operation_processing_queue; 34 | } 35 | 36 | @interface AFXMLRequestOperation () 37 | @property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser; 38 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 39 | @property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument; 40 | #endif 41 | @property (readwrite, nonatomic, strong) NSError *XMLError; 42 | @end 43 | 44 | @implementation AFXMLRequestOperation 45 | @synthesize responseXMLParser = _responseXMLParser; 46 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 47 | @synthesize responseXMLDocument = _responseXMLDocument; 48 | #endif 49 | @synthesize XMLError = _XMLError; 50 | 51 | + (AFXMLRequestOperation *)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 52 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 53 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure 54 | { 55 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 56 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 57 | if (success) { 58 | success(operation.request, operation.response, responseObject); 59 | } 60 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 61 | if (failure) { 62 | failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]); 63 | } 64 | }]; 65 | 66 | return requestOperation; 67 | } 68 | 69 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 70 | + (AFXMLRequestOperation *)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest 71 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success 72 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure 73 | { 74 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 75 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) { 76 | if (success) { 77 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 78 | success(operation.request, operation.response, XMLDocument); 79 | } 80 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 81 | if (failure) { 82 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 83 | failure(operation.request, operation.response, error, XMLDocument); 84 | } 85 | }]; 86 | 87 | return requestOperation; 88 | } 89 | #endif 90 | 91 | 92 | - (NSXMLParser *)responseXMLParser { 93 | if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) { 94 | self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData]; 95 | } 96 | 97 | return _responseXMLParser; 98 | } 99 | 100 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 101 | - (NSXMLDocument *)responseXMLDocument { 102 | if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) { 103 | NSError *error = nil; 104 | self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error]; 105 | self.XMLError = error; 106 | } 107 | 108 | return _responseXMLDocument; 109 | } 110 | #endif 111 | 112 | - (NSError *)error { 113 | if (_XMLError) { 114 | return _XMLError; 115 | } else { 116 | return [super error]; 117 | } 118 | } 119 | 120 | #pragma mark - NSOperation 121 | 122 | - (void)cancel { 123 | [super cancel]; 124 | 125 | self.responseXMLParser.delegate = nil; 126 | } 127 | 128 | #pragma mark - AFHTTPRequestOperation 129 | 130 | + (NSSet *)acceptableContentTypes { 131 | return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; 132 | } 133 | 134 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 135 | return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request]; 136 | } 137 | 138 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 139 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 140 | { 141 | #pragma clang diagnostic push 142 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 143 | self.completionBlock = ^ { 144 | if ([self isCancelled]) { 145 | return; 146 | } 147 | 148 | dispatch_async(xml_request_operation_processing_queue(), ^(void) { 149 | NSXMLParser *XMLParser = self.responseXMLParser; 150 | 151 | if (self.error) { 152 | if (failure) { 153 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 154 | failure(self, self.error); 155 | }); 156 | } 157 | } else { 158 | if (success) { 159 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 160 | success(self, XMLParser); 161 | }); 162 | } 163 | } 164 | }); 165 | }; 166 | #pragma clang diagnostic pop 167 | } 168 | 169 | @end 170 | -------------------------------------------------------------------------------- /AFNetworking/AFImageRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFImageRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFImageRequestOperation.h" 24 | 25 | static dispatch_queue_t af_image_request_operation_processing_queue; 26 | static dispatch_queue_t image_request_operation_processing_queue() { 27 | if (af_image_request_operation_processing_queue == NULL) { 28 | af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", 0); 29 | } 30 | 31 | return af_image_request_operation_processing_queue; 32 | } 33 | 34 | @interface AFImageRequestOperation () 35 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 36 | @property (readwrite, nonatomic, strong) UIImage *responseImage; 37 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 38 | @property (readwrite, nonatomic, strong) NSImage *responseImage; 39 | #endif 40 | @end 41 | 42 | @implementation AFImageRequestOperation 43 | @synthesize responseImage = _responseImage; 44 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 45 | @synthesize imageScale = _imageScale; 46 | #endif 47 | 48 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 49 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 50 | success:(void (^)(UIImage *image))success 51 | { 52 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { 53 | if (success) { 54 | success(image); 55 | } 56 | } failure:nil]; 57 | } 58 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 59 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 60 | success:(void (^)(NSImage *image))success 61 | { 62 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) { 63 | if (success) { 64 | success(image); 65 | } 66 | } failure:nil]; 67 | } 68 | #endif 69 | 70 | 71 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 72 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 73 | imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock 74 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 75 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 76 | { 77 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 78 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 79 | if (success) { 80 | UIImage *image = responseObject; 81 | if (imageProcessingBlock) { 82 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 83 | UIImage *processedImage = imageProcessingBlock(image); 84 | 85 | dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 86 | success(operation.request, operation.response, processedImage); 87 | }); 88 | }); 89 | } else { 90 | success(operation.request, operation.response, image); 91 | } 92 | } 93 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 94 | if (failure) { 95 | failure(operation.request, operation.response, error); 96 | } 97 | }]; 98 | 99 | 100 | return requestOperation; 101 | } 102 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 103 | + (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 104 | imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock 105 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 106 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 107 | { 108 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 109 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 110 | if (success) { 111 | NSImage *image = responseObject; 112 | if (imageProcessingBlock) { 113 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 114 | NSImage *processedImage = imageProcessingBlock(image); 115 | 116 | dispatch_async(requestOperation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 117 | success(operation.request, operation.response, processedImage); 118 | }); 119 | }); 120 | } else { 121 | success(operation.request, operation.response, image); 122 | } 123 | } 124 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 125 | if (failure) { 126 | failure(operation.request, operation.response, error); 127 | } 128 | }]; 129 | 130 | return requestOperation; 131 | } 132 | #endif 133 | 134 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 135 | self = [super initWithRequest:urlRequest]; 136 | if (!self) { 137 | return nil; 138 | } 139 | 140 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 141 | self.imageScale = [[UIScreen mainScreen] scale]; 142 | #endif 143 | 144 | return self; 145 | } 146 | 147 | 148 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 149 | - (UIImage *)responseImage { 150 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 151 | UIImage *image = [UIImage imageWithData:self.responseData]; 152 | 153 | self.responseImage = [UIImage imageWithCGImage:[image CGImage] scale:self.imageScale orientation:image.imageOrientation]; 154 | } 155 | 156 | return _responseImage; 157 | } 158 | 159 | - (void)setImageScale:(CGFloat)imageScale { 160 | #pragma clang diagnostic push 161 | #pragma clang diagnostic ignored "-Wfloat-equal" 162 | if (imageScale == _imageScale) { 163 | return; 164 | } 165 | #pragma clang diagnostic pop 166 | 167 | _imageScale = imageScale; 168 | 169 | self.responseImage = nil; 170 | } 171 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 172 | - (NSImage *)responseImage { 173 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 174 | // Ensure that the image is set to it's correct pixel width and height 175 | NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData]; 176 | self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; 177 | [self.responseImage addRepresentation:bitimage]; 178 | } 179 | 180 | return _responseImage; 181 | } 182 | #endif 183 | 184 | #pragma mark - AFHTTPRequestOperation 185 | 186 | + (NSSet *)acceptableContentTypes { 187 | 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]; 188 | } 189 | 190 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 191 | static NSSet * _acceptablePathExtension = nil; 192 | static dispatch_once_t onceToken; 193 | dispatch_once(&onceToken, ^{ 194 | _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; 195 | }); 196 | 197 | return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request]; 198 | } 199 | 200 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 201 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 202 | { 203 | #pragma clang diagnostic push 204 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 205 | self.completionBlock = ^ { 206 | if ([self isCancelled]) { 207 | return; 208 | } 209 | 210 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 211 | if (self.error) { 212 | if (failure) { 213 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 214 | failure(self, self.error); 215 | }); 216 | } 217 | } else { 218 | if (success) { 219 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 220 | UIImage *image = nil; 221 | #elif __MAC_OS_X_VERSION_MIN_REQUIRED 222 | NSImage *image = nil; 223 | #endif 224 | 225 | image = self.responseImage; 226 | 227 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 228 | success(self, image); 229 | }); 230 | } 231 | } 232 | }); 233 | }; 234 | #pragma clang diagnostic pop 235 | } 236 | 237 | @end 238 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | AFNetworking 2 | 3 | AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL: 4 | 5 | ``` objective-c 6 | NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]; 7 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 8 | AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 9 | NSLog(@"App.net Global Stream: %@", JSON); 10 | } failure:nil]; 11 | [operation start]; 12 | ``` 13 | 14 | Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. 15 | 16 | Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! 17 | 18 | ## How To Get Started 19 | 20 | - [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps 21 | - Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki) 22 | - Check out the [complete documentation](http://afnetworking.github.com/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking 23 | - Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application 24 | - Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers 25 | 26 | ## Overview 27 | 28 | AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend. 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 |
Core
AFURLConnectionOperationAn NSOperation that implements the NSURLConnection delegate methods.
HTTP Requests
AFHTTPRequestOperationA 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.
AFJSONRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with JSON response data.
AFXMLRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with XML response data.
AFPropertyListRequestOperationA subclass of AFHTTPRequestOperation for downloading and deserializing objects with property list response data.
HTTP Client
AFHTTPClient 60 | Captures the common patterns of communicating with an web application over HTTP, including: 61 | 62 |
    63 |
  • Making requests from relative paths of a base URL
  • 64 |
  • Setting HTTP headers to be added automatically to requests
  • 65 |
  • Authenticating requests with HTTP Basic credentials or an OAuth token
  • 66 |
  • Managing an NSOperationQueue for requests made by the client
  • 67 |
  • Generating query strings or HTTP bodies from an NSDictionary
  • 68 |
  • Constructing multipart form requests
  • 69 |
  • Automatically parsing HTTP response data into its corresponding object representation
  • 70 |
  • Monitoring and responding to changes in network reachability
  • 71 |
72 |
Images
AFImageRequestOperationA subclass of AFHTTPRequestOperation for downloading and processing images.
UIImageView+AFNetworkingAdds methods to UIImageView for loading remote images asynchronously from a URL.
85 | 86 | ## Example Usage 87 | 88 | ### XML Request 89 | 90 | ``` objective-c 91 | 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"]]; 92 | AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) { 93 | XMLParser.delegate = self; 94 | [XMLParser parse]; 95 | } failure:nil]; 96 | [operation start]; 97 | ``` 98 | 99 | ### Image Request 100 | 101 | ``` objective-c 102 | UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; 103 | [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; 104 | ``` 105 | 106 | ### API Client Request 107 | 108 | ``` objective-c 109 | // AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates 110 | [[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) { 111 | NSLog(@"App.net Global Stream: %@", JSON); 112 | } failure:nil]; 113 | ``` 114 | 115 | ### File Upload with Progress Callback 116 | 117 | ``` objective-c 118 | NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; 119 | AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 120 | NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); 121 | NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) { 122 | [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; 123 | }]; 124 | 125 | AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; 126 | [operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 127 | NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 128 | }]; 129 | [operation start]; 130 | ``` 131 | 132 | ### Streaming Request 133 | 134 | ``` objective-c 135 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]]; 136 | 137 | AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease]; 138 | operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]]; 139 | operation.outputStream = [NSOutputStream outputStreamToMemory]; 140 | [operation start]; 141 | ``` 142 | 143 | ## Requirements 144 | 145 | AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above. 146 | 147 | For compatibility with iOS 4.3, use the latest 0.10.x release. 148 | 149 | ### ARC 150 | 151 | AFNetworking uses ARC as of its 1.0 release. 152 | 153 | If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag. 154 | 155 | To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking. 156 | 157 | ## Credits 158 | 159 | AFNetworking was created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). 160 | 161 | AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). 162 | 163 | And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). 164 | 165 | ## Contact 166 | 167 | Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking)) 168 | 169 | ### Creators 170 | 171 | [Mattt Thompson](http://github.com/mattt) 172 | [@mattt](https://twitter.com/mattt) 173 | 174 | [Scott Raymond](http://github.com/sco) 175 | [@sco](https://twitter.com/sco) 176 | 177 | ## License 178 | 179 | AFNetworking is available under the MIT license. See the LICENSE file for more info. 180 | -------------------------------------------------------------------------------- /AFNetworking/AFHTTPRequestOperation.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFHTTPRequestOperation.h" 24 | #import 25 | 26 | // Workaround for change in imp_implementationWithBlock() with Xcode 4.5 27 | #if defined(__IPHONE_6_0) || defined(__MAC_10_8) 28 | #define AF_CAST_TO_BLOCK id 29 | #else 30 | #define AF_CAST_TO_BLOCK __bridge void * 31 | #endif 32 | 33 | NSSet * AFContentTypesFromHTTPHeader(NSString *string) { 34 | if (!string) { 35 | return nil; 36 | } 37 | 38 | NSArray *mediaRanges = [string componentsSeparatedByString:@","]; 39 | NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count]; 40 | 41 | [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, NSUInteger idx, BOOL *stop) { 42 | NSRange parametersRange = [mediaRange rangeOfString:@";"]; 43 | if (parametersRange.location != NSNotFound) { 44 | mediaRange = [mediaRange substringToIndex:parametersRange.location]; 45 | } 46 | 47 | mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 48 | 49 | if (mediaRange.length > 0) { 50 | [mutableContentTypes addObject:mediaRange]; 51 | } 52 | }]; 53 | 54 | return [NSSet setWithSet:mutableContentTypes]; 55 | } 56 | 57 | static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) { 58 | NSMutableString *string = [NSMutableString string]; 59 | 60 | NSRange range = NSMakeRange([indexSet firstIndex], 1); 61 | while (range.location != NSNotFound) { 62 | NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location]; 63 | while (nextIndex == range.location + range.length) { 64 | range.length++; 65 | nextIndex = [indexSet indexGreaterThanIndex:nextIndex]; 66 | } 67 | 68 | if (string.length) { 69 | [string appendString:@","]; 70 | } 71 | 72 | if (range.length == 1) { 73 | [string appendFormat:@"%lu", (long)range.location]; 74 | } else { 75 | NSUInteger firstIndex = range.location; 76 | NSUInteger lastIndex = firstIndex + range.length - 1; 77 | [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex]; 78 | } 79 | 80 | range.location = nextIndex; 81 | range.length = 1; 82 | } 83 | 84 | return string; 85 | } 86 | 87 | static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) { 88 | Method originalMethod = class_getClassMethod(klass, selector); 89 | IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block); 90 | class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod)); 91 | } 92 | 93 | #pragma mark - 94 | 95 | @interface AFHTTPRequestOperation () 96 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 97 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; 98 | @property (readwrite, nonatomic, strong) NSError *HTTPError; 99 | @property (assign) long long totalContentLength; 100 | @property (assign) long long offsetContentLength; 101 | @end 102 | 103 | @implementation AFHTTPRequestOperation 104 | @synthesize HTTPError = _HTTPError; 105 | @synthesize successCallbackQueue = _successCallbackQueue; 106 | @synthesize failureCallbackQueue = _failureCallbackQueue; 107 | @synthesize totalContentLength = _totalContentLength; 108 | @synthesize offsetContentLength = _offsetContentLength; 109 | @dynamic request; 110 | @dynamic response; 111 | 112 | - (void)dealloc { 113 | if (_successCallbackQueue) { 114 | #if !OS_OBJECT_USE_OBJC 115 | dispatch_release(_successCallbackQueue); 116 | #endif 117 | _successCallbackQueue = NULL; 118 | } 119 | 120 | if (_failureCallbackQueue) { 121 | #if !OS_OBJECT_USE_OBJC 122 | dispatch_release(_failureCallbackQueue); 123 | #endif 124 | _failureCallbackQueue = NULL; 125 | } 126 | } 127 | 128 | - (NSError *)error { 129 | if (self.response && !self.HTTPError) { 130 | if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) { 131 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; 132 | [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey]; 133 | [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; 134 | [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey]; 135 | [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey]; 136 | 137 | if (![self hasAcceptableStatusCode]) { 138 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 139 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected status code in (%@), got %d", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey]; 140 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo]; 141 | } else if (![self hasAcceptableContentType]) { 142 | // Don't invalidate content type if there is no content 143 | if ([self.responseData length] > 0) { 144 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedString(@"Expected content type %@, got %@", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; 145 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; 146 | } 147 | } 148 | } 149 | } 150 | 151 | if (self.HTTPError) { 152 | return self.HTTPError; 153 | } else { 154 | return [super error]; 155 | } 156 | } 157 | 158 | - (void)pause { 159 | unsigned long long offset = 0; 160 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 161 | offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; 162 | } else { 163 | offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; 164 | } 165 | 166 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; 167 | if ([[self.response allHeaderFields] valueForKey:@"ETag"]) { 168 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; 169 | } 170 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; 171 | self.request = mutableURLRequest; 172 | 173 | [super pause]; 174 | } 175 | 176 | - (BOOL)hasAcceptableStatusCode { 177 | if (!self.response) { 178 | return NO; 179 | } 180 | 181 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 182 | return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode]; 183 | } 184 | 185 | - (BOOL)hasAcceptableContentType { 186 | if (!self.response) { 187 | return NO; 188 | } 189 | 190 | // According to RFC 2616: 191 | // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". 192 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html 193 | NSString *contentType = [self.response MIMEType]; 194 | if (!contentType) { 195 | contentType = @"application/octet-stream"; 196 | } 197 | 198 | return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType]; 199 | } 200 | 201 | - (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue { 202 | if (successCallbackQueue != _successCallbackQueue) { 203 | if (_successCallbackQueue) { 204 | #if !OS_OBJECT_USE_OBJC 205 | dispatch_release(_successCallbackQueue); 206 | #endif 207 | _successCallbackQueue = NULL; 208 | } 209 | 210 | if (successCallbackQueue) { 211 | #if !OS_OBJECT_USE_OBJC 212 | dispatch_retain(successCallbackQueue); 213 | #endif 214 | _successCallbackQueue = successCallbackQueue; 215 | } 216 | } 217 | } 218 | 219 | - (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue { 220 | if (failureCallbackQueue != _failureCallbackQueue) { 221 | if (_failureCallbackQueue) { 222 | #if !OS_OBJECT_USE_OBJC 223 | dispatch_release(_failureCallbackQueue); 224 | #endif 225 | _failureCallbackQueue = NULL; 226 | } 227 | 228 | if (failureCallbackQueue) { 229 | #if !OS_OBJECT_USE_OBJC 230 | dispatch_retain(failureCallbackQueue); 231 | #endif 232 | _failureCallbackQueue = failureCallbackQueue; 233 | } 234 | } 235 | } 236 | 237 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 238 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 239 | { 240 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. 241 | #pragma clang diagnostic push 242 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 243 | self.completionBlock = ^{ 244 | if ([self isCancelled]) { 245 | return; 246 | } 247 | 248 | if (self.error) { 249 | if (failure) { 250 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 251 | failure(self, self.error); 252 | }); 253 | } 254 | } else { 255 | if (success) { 256 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 257 | success(self, self.responseData); 258 | }); 259 | } 260 | } 261 | }; 262 | #pragma clang diagnostic pop 263 | } 264 | 265 | #pragma mark - AFHTTPRequestOperation 266 | 267 | + (NSIndexSet *)acceptableStatusCodes { 268 | return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; 269 | } 270 | 271 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes { 272 | NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]]; 273 | [mutableStatusCodes addIndexes:statusCodes]; 274 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(id _self) { 275 | return mutableStatusCodes; 276 | }); 277 | } 278 | 279 | + (NSSet *)acceptableContentTypes { 280 | return nil; 281 | } 282 | 283 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes { 284 | NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES]; 285 | [mutableContentTypes unionSet:contentTypes]; 286 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(id _self) { 287 | return mutableContentTypes; 288 | }); 289 | } 290 | 291 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 292 | if ([[self class] isEqual:[AFHTTPRequestOperation class]]) { 293 | return YES; 294 | } 295 | 296 | return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])]; 297 | } 298 | 299 | #pragma mark - NSURLConnectionDelegate 300 | 301 | - (void)connection:(NSURLConnection *)connection 302 | didReceiveResponse:(NSURLResponse *)response 303 | { 304 | self.response = (NSHTTPURLResponse *)response; 305 | 306 | // Set Content-Range header if status code of response is 206 (Partial Content) 307 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7 308 | long long totalContentLength = self.response.expectedContentLength; 309 | long long fileOffset = 0; 310 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 311 | if (statusCode == 206) { 312 | NSString *contentRange = [self.response.allHeaderFields valueForKey:@"Content-Range"]; 313 | if ([contentRange hasPrefix:@"bytes"]) { 314 | NSArray *byteRanges = [contentRange componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" -/"]]; 315 | if ([byteRanges count] == 4) { 316 | fileOffset = [[byteRanges objectAtIndex:1] longLongValue]; 317 | totalContentLength = [[byteRanges objectAtIndex:2] longLongValue] ?: -1; // if this is "*", it's converted to 0, but -1 is default. 318 | } 319 | } 320 | } else { 321 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 322 | [self.outputStream setProperty:[NSNumber numberWithInteger:0] forKey:NSStreamFileCurrentOffsetKey]; 323 | } else { 324 | if ([[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length] > 0) { 325 | self.outputStream = [NSOutputStream outputStreamToMemory]; 326 | 327 | NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 328 | for (NSString *runLoopMode in self.runLoopModes) { 329 | [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; 330 | } 331 | } 332 | } 333 | } 334 | 335 | self.offsetContentLength = MAX(fileOffset, 0); 336 | self.totalContentLength = totalContentLength; 337 | 338 | [self.outputStream open]; 339 | } 340 | 341 | @end 342 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | = 1.0 / 2012-10-15 2 | 3 | * AFNetworking now requires iOS 5 / Mac OSX 10.7 or higher (Mattt Thompson) 4 | 5 | * AFNetworking now uses Automatic Reference Counting (ARC) (Mattt Thompson) 6 | 7 | * AFNetworking raises compiler warnings for missing features when 8 | SystemConfiguration or CoreServices / MobileCoreServices frameworks are not 9 | included in the project and imported in the precompiled headers (Mattt 10 | Thompson) 11 | 12 | * AFNetworking now raises compiler error when not compiled with ARC (Steven 13 | Fisher) 14 | 15 | * Add `NSCoding` and `NSCopying` protocol conformance to 16 | `AFURLConnectionOperation` and `AFHTTPClient` (Mattt Thompson) 17 | 18 | * Add substantial improvements HTTP multipart streaming support, having 19 | files streamed directly from disk and read sequentially from a custom input 20 | stream (Max Lansing, Stan Chang Khin Boon, Mattt Thompson) 21 | 22 | * Add `AFMultipartFormData -throttleBandwidthWithPacketSize:delay:` as 23 | workaround to issues when uploading over 3G (Mattt Thompson) 24 | 25 | * Add request and response to `userInfo` of errors returned from failing 26 | `AFHTTPRequestOperation` (Mattt Thompson) 27 | 28 | * Add `userInfo` dictionary with current status in reachability changes 29 | (Mattt Thompson) 30 | 31 | * Add `Accept` header for image requests in `UIImageView` category (Bratley 32 | Lower) 33 | 34 | * Add explicit declaration of `NSURLConnection` delegate methods so that 35 | they can be overridden in subclasses (Mattt Thompson, Evan Grim) 36 | 37 | * Add parameter validation to match conditions specified in documentation 38 | (Jason Brennan, Mattt Thompson) 39 | 40 | * Add import to `UIKit` to avoid build errors from `UIDevice` references in 41 | `User-Agent` default header (Blake Watters) 42 | 43 | * Remove `AFJSONUtilities` in favor of `NSJSONSerialization` (Mattt Thompson) 44 | 45 | * Remove `extern` declaration of `AFURLEncodedStringFromStringWithEncoding` 46 | function (`CFURLCreateStringByAddingPercentEscapes` should be used instead) 47 | (Mattt Thompson) 48 | 49 | * Remove `setHTTPShouldHandleCookies:NO` from `AFHTTPClient` (@phamsonha, 50 | Mattt Thompson) 51 | 52 | * Remove `dispatch_retain` / `dispatch_release` with ARC in iOS 6 (Benoit 53 | Bourdon) 54 | 55 | * Fix threading issue with `AFNetworkActivityIndicatorManager` (Eric Patey) 56 | 57 | * Fix issue where `AFNetworkActivityIndicatorManager` count could become 58 | negative (@ap4y) 59 | 60 | * Fix properties to explicitly set options to suppress warnings (Wen-Hao 61 | Lue, Mattt Thompson) 62 | 63 | * Fix compiler warning caused by mismatched types in upload / download 64 | progress blocks (Gareth du Plooy, tomas.a) 65 | 66 | * Fix weak / strong variable relationships in `completionBlock` (Peter 67 | Steinberger) 68 | 69 | * Fix string formatting syntax warnings caused by type mismatch (David 70 | Keegan, Steven Fisher, George Cox) 71 | 72 | * Fix minor potential security vulnerability by explicitly using string 73 | format in NSError localizedDescription value in userInfo (Steven Fisher) 74 | 75 | * Fix `AFURLConnectionOperation -pause` by adding state checks to prevent 76 | likely memory issues when resuming (Mattt Thompson) 77 | 78 | * Fix warning caused by miscast of type when 79 | `CLANG_WARN_IMPLICIT_SIGN_CONVERSION` is set (Steven Fisher) 80 | 81 | * Fix incomplete implementation warning in example code (Steven Fisher) 82 | 83 | * Fix warning caused by using `==` comparator on floats (Steven Fisher) 84 | 85 | * Fix iOS 4 bug where file URLs return `NSURLResponse` rather than 86 | `NSHTTPURLResponse` objects (Leo Lobato) 87 | 88 | * Fix calculation of finished operations in batch operation progress 89 | callback (Mattt Thompson) 90 | 91 | * Fix documentation typos (Steven Fisher, Matthias Wessendorf, 92 | jorge@miv.uk.com) 93 | 94 | * Fix `hasAcceptableStatusCode` to return true after a network failure (Tony 95 | Million) 96 | 97 | * Fix warning about missing prototype for private static method (Stephan 98 | Diederich) 99 | 100 | * Fix issue where `nil` content type resulted in unacceptable content type 101 | (Mattt Thompson) 102 | 103 | * Fix bug related to setup and scheduling of output stream (Stephen Tramer) 104 | 105 | * Fix AFContentTypesFromHTTPHeader to correctly handle comma-delimited 106 | content types (Peyman, Mattt Thompson, @jsm174) 107 | 108 | * Fix crash caused by `_networkReachability` not being set to `NULL` after 109 | releasing (Blake Watters) 110 | 111 | * Fix Podspec to correctly import required headers and use ARC (Eloy Durán, 112 | Blake Watters) 113 | 114 | * Fix query string parameter escaping to leave square brackets unescaped 115 | (Mattt Thompson) 116 | 117 | * Fix query string parameter encoding of `NSNull` values (Daniel Rinser) 118 | 119 | * Fix error caused by referencing `__IPHONE_OS_VERSION_MIN_REQUIRED` without 120 | importing `Availability.h` (Blake Watters) 121 | 122 | * Update example to use App.net API, as Twitter shut off its unauthorized 123 | access to the public timeline (Mattt Thompson) 124 | 125 | * Update `AFURLConnectionOperation` to replace `NSAutoReleasePool` with 126 | `@autoreleasepool` (Mattt Thompson) 127 | 128 | * Update `AFHTTPClient` operation queue to specify 129 | `NSOperationQueueDefaultMaxConcurrentOperationCount` rather than 130 | previously-defined constant (Mattt Thompson) 131 | 132 | * Update `AFHTTPClient -initWithBaseURL` to automatically append trailing 133 | slash, so as to fix common issue where default path is not respected without 134 | trailing slash (Steven Fisher) 135 | 136 | * Update default `AFHTTPClient` `User-Agent` header strings (Mattt Thompson, 137 | Steven Fisher) 138 | 139 | * Update icons for iOS example application (Mattt Thompson) 140 | 141 | * Update `numberOfCompletedOperations` variable in progress block to be 142 | renamed to `numberOfFinishedOperations` (Mattt Thompson) 143 | 144 | 145 | = 0.10.0 / 2012-06-26 146 | 147 | * Add Twitter Mac Example application (Mattt Thompson) 148 | 149 | * Add note in README about how to set `-fno-objc-arc` flag for multiple files 150 | at once (Pål Brattberg) 151 | 152 | * Add note in README about 64-bit architecture requirement (@rmuginov, Mattt 153 | Thompson) 154 | 155 | * Add note in `AFNetworkActivityIndicatorManager` about not having to manually 156 | manage animation state (Mattt Thompson) 157 | 158 | * Add missing block parameter name for `imageProcessingBlock` (Francois 159 | Lambert) 160 | 161 | * Add NextiveJson to list of supported JSON libraries (Mattt Thompson) 162 | 163 | * Restore iOS 4.0 compatibility with `addAcceptableStatusCodes:` and 164 | `addAcceptableContentTypes:` (Zachary Waldowski) 165 | 166 | * Update `AFHTTPClient` to use HTTP pipelining for `GET` and `HEAD` requests by 167 | default (Mattt Thompson) 168 | 169 | * Remove @private ivar declaration in headers (Peter Steinberger, Mattt 170 | Thompson) 171 | 172 | * Fix potential premature deallocation of _skippedCharacterSet (Tom Wanielista, 173 | Mattt Thompson) 174 | 175 | * Fix potential issue in `setOutputStream` by closing any existing 176 | `outputStream` (Mattt Thompson) 177 | 178 | * Fix filename in AFHTTPClient header (Steven Fisher) 179 | 180 | * Fix documentation for UIImageView+AFNetworking (Mattt Thompson) 181 | 182 | * Fix HTTP multipart form format, which caused issues with Tornado web server 183 | (Matt Chen) 184 | 185 | * Fix `AFHTTPClient` to not append empty data into multipart form data (Jon 186 | Parise) 187 | 188 | * Fix URL encoding normalization to not conditionally escape percent-encoded 189 | strings (João Prado Maia, Kendall Helmstetter Gelner, @cysp, Mattt Thompson) 190 | 191 | * Fix `AFHTTPClient` documentation reference of 192 | `HTTPRequestOperationWithRequest:success:failure` (Shane Vitarana) 193 | 194 | * Add `AFURLRequestOperation -setRedirectResponseBlock:` (Kevin Harwood) 195 | 196 | * Fix `AFURLConnectionOperation` compilation error by conditionally importing 197 | UIKit framework (Steven Fisher) 198 | 199 | * Fix issue where image processing block is not called correctly with success 200 | block in `AFImageRequestOperation` (Sergey Gavrilyuk) 201 | 202 | * Fix leaked dispatch group in batch operations (@andyegorov, Mattt Thompson) 203 | 204 | * Fix support for non-LLVM compilers in `AFNetworkActivityIndicatorManager` 205 | (Abraham Vegh, Bill Williams, Mattt Thompson) 206 | 207 | * Fix AFHTTPClient to not add unnecessary data when constructing multipart form 208 | request with nil parameters (Taeho Kim) 209 | 210 | = 1.0RC1 / 2012-04-25 211 | 212 | * Add `AFHTTPRequestOperation +addAcceptableStatusCodes / 213 | +addAcceptableContentTypes` to dynamically add acceptable status codes and 214 | content types on the class level (Mattt Thompson) 215 | 216 | * Add support for compound and complex `Accept` headers that include multiple 217 | content types and / or specify a particular character encoding (Mattt Thompson) 218 | 219 | * Add `AFURLConnectionOperation 220 | -setShouldExecuteAsBackgroundTaskWithExpirationHandler:` to have operations 221 | finish once an app becomes inactive (Mattt Thompson) 222 | 223 | * Add support for pausing / resuming request operations (Peter Steinberger, 224 | Mattt Thompson) 225 | 226 | * Improve network reachability functionality in `AFHTTPClient`, including a 227 | distinction between WWan and WiFi reachability (Kevin Harwood, Mattt Thompson) 228 | 229 | 230 | = 0.9.2 / 2012-04-25 231 | 232 | * Add thread safety to `AFNetworkActivityIndicator` (Peter Steinberger, Mattt 233 | Thompson) 234 | 235 | * Document requirement of available JSON libraries for decoding responses in 236 | `AFJSONRequestOperation` and parameter encoding in `AFHTTPClient` (Mattt 237 | Thompson) 238 | 239 | * Fix `AFHTTPClient` parameter encoding (Mattt Thompson) 240 | 241 | * Fix `AFJSONEncode` and `AFJSONDecode` to use `SBJsonWriter` and 242 | `SBJsonParser` instead of `NSObject+SBJson` (Oliver Eikemeier) 243 | 244 | * Fix bug where `AFJSONDecode` does not return errors (Alex Michaud) 245 | 246 | * Fix compiler warning for undeclared 247 | `AFQueryStringComponentFromKeyAndValueWithEncoding` function (Mattt Thompson) 248 | 249 | * Fix cache policy for URL requests (Peter Steinberger) 250 | 251 | * Fix race condition bug in `UIImageView+AFNetworking` caused by incorrectly 252 | nil-ing request operations (John Wu) 253 | 254 | * Fix reload button in Twitter example (Peter Steinberger) 255 | 256 | * Improve batched operation by deferring execution of batch completion block 257 | until all component request completion blocks have finished (Patrick Hernandez, 258 | Kevin Harwood, Mattt Thompson) 259 | 260 | * Improve performance of image request decoding by dispatching to background 261 | queue (Mattt Thompson) 262 | 263 | * Revert `AFImageCache` to cache image objects rather than `NSPurgeableData` 264 | (Tony Million, Peter Steinberger, Mattt Thompson) 265 | 266 | * Remove unnecessary KVO `willChangeValueForKey:` / `didChangeValueForKey:` 267 | calls (Peter Steinberger) 268 | 269 | * Remove unnecessary @private ivar declarations in headers (Peter Steinberger, 270 | Mattt Thompson) 271 | 272 | * Remove @try-@catch block wrapping network thread entry point (Charles T. Ahn) 273 | 274 | 275 | = 0.9.1 / 2012-03-19 276 | 277 | * Create Twitter example application (Mattt Thompson) 278 | 279 | * Add support for nested array and dictionary parameters for query string and 280 | form-encoded requests (Mathieu Hausherr, Josh Chung, Mattt Thompson) 281 | 282 | * Add `AFURLConnectionOperation -setCacheResponseBlock:`, which allows the 283 | behavior of the `NSURLConnectionDelegate` method 284 | `-connection:willCacheResponse:` to be overridden without subclassing (Mattt 285 | Thompson) 286 | 287 | * Add `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` macros for 288 | NSURLConnection authentication delegate methods (Mattt Thompson) 289 | 290 | * Add properties for custom success / failure callback queues (Peter 291 | Steinberger) 292 | 293 | * Add notifications for network reachability changes to `AFHTTPClient` (Mattt 294 | Thompson) 295 | 296 | * Add `AFHTTPClient -patchPath:` convenience method (Mattt Thompson) 297 | 298 | * Add support for NextiveJson (Adrian Kosmaczewski) 299 | 300 | * Improve network reachability checks (C. Bess) 301 | 302 | * Improve NSIndexSet formatting in error strings (Jon Parise) 303 | 304 | * Document crashing behavior in iOS 4 loading a file:// URL (Mattt Thompson) 305 | 306 | * Fix crash caused by `AFHTTPClient -cancelAllHTTPOperationsWithMethod:` not 307 | checking operation to be instance of `AFHTTPRequestOperation` (Mattt Thompson) 308 | 309 | * Fix crash caused by passing `nil` URL in requests (Sam Soffes) 310 | 311 | * Fix errors caused by connection property not being nil'd out after an 312 | operation finishes (Kevin Harwood, @zdzisiekpu) 313 | 314 | * Fix crash caused by passing `NULL` error pointer when setting `NSInvocation` 315 | in `AFJSONEncode` and `AFJSONDecode` (Tyler Stromberg) 316 | 317 | * Fix batch operation completion block returning on background thread (Patrick 318 | Hernandez) 319 | 320 | * Fix documentation for UIImageView+AFNetworking (Dominic Dagradi) 321 | 322 | * Fix race condition caused by `AFURLConnectionOperation` being cancelled on 323 | main thread, rather than network thread (Erik Olsson) 324 | 325 | * Fix `AFURLEncodedStringFromStringWithEncoding` to correctly handle cases 326 | where % is used as a literal rather than as part of a percent escape code 327 | (Mattt Thompson) 328 | 329 | * Fix missing comma in `+defaultAcceptableContentTypes` for 330 | `AFImageRequestOperation` (Michael Schneider) 331 | 332 | 333 | = 0.9.0 / 2012-01-23 334 | 335 | * Add thread-safe behavior to `AFURLConnectionOperation` (Mattt Thompson) 336 | 337 | * Add batching of operations for `AFHTTPClient` (Mattt Thompson) 338 | 339 | * Add authentication challenge callback block to override default 340 | implementation of `connection:didReceiveAuthenticationChallenge:` in 341 | `AFURLConnectionOperation` (Mattt Thompson) 342 | 343 | * Add `_AFNETWORKING_PREFER_NSJSONSERIALIZATION_`, which, when defined, 344 | short-circuits the standard preference ordering used in `AFJSONEncode` and 345 | `AFJSONDecode` to use `NSJSONSerialization` when available, falling back on 346 | third-party-libraries. (Mattt Thompson, Shane Vitarana) 347 | 348 | * Add custom `description` for `AFURLConnectionOperation` and `AFHTTPClient` 349 | (Mattt Thompson) 350 | 351 | * Add `text/javascript` to default acceptable content types for 352 | `AFJSONRequestOperation` (Jake Boxer) 353 | 354 | * Add `imageScale` property to change resolution of images constructed from 355 | cached data (Štěpán Petrů) 356 | 357 | * Add note about third party JSON libraries in README (David Keegan) 358 | 359 | * `AFQueryStringFromParametersWithEncoding` formats `NSArray` values in the 360 | form `key[]=value1&key[]=value2` instead of `key=(value1,value2)` (Dan Thorpe) 361 | 362 | * `AFImageRequestOperation -responseImage` on OS X uses `NSBitmapImageRep` to 363 | determine the correct pixel dimensions of the image (David Keegan) 364 | 365 | * `AFURLConnectionOperation` `connection` has memory management policy `assign` 366 | to avoid retain cycles caused by `NSURLConnection` retaining its delegate 367 | (Mattt Thompson) 368 | 369 | * `AFURLConnectionOperation` calls super implementation for `-isReady`, 370 | following the guidelines for `NSOperation` subclasses (Mattt Thompson) 371 | 372 | * `UIImageView -setImageWithURL:` and related methods call success callback 373 | after setting image (Cameron Boehmer) 374 | 375 | * Cancel request if an authentication challenge has no suitable credentials in 376 | `AFURLConnectionOperation -connection:didReceiveAuthenticationChallenge:` 377 | (Jorge Bernal) 378 | 379 | * Remove exception from 380 | `multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` 381 | raised when certain HTTP methods are used. (Mattt Thompson) 382 | 383 | * Remove `AFImageCache` from public API, moving it into private implementation 384 | of `UIImageView+AFNetworking` (Mattt Thompson) 385 | 386 | * Mac example application makes better use of AppKit technologies and 387 | conventions (Mattt Thompson) 388 | 389 | * Fix issue with multipart form boundaries in `AFHTTPClient 390 | -multipartFormRequestWithMethod:path:parameters:constructing BodyWithBlock:` 391 | (Ray Morgan, Mattt Thompson, Sam Soffes) 392 | 393 | * Fix "File Upload with Progress Callback" code snippet in README (Larry Legend) 394 | 395 | * Fix to SBJSON invocations in `AFJSONEncode` and `AFJSONDecode` (Matthias 396 | Tretter, James Frye) 397 | 398 | * Fix documentation for `AFHTTPClient requestWithMethod:path:parameters:` 399 | (Michael Parker) 400 | 401 | * Fix `Content-Disposition` headers used for multipart form construction 402 | (Michael Parker) 403 | 404 | * Add network reachability status change callback property to `AFHTTPClient`. 405 | (Mattt Thompson, Kevin Harwood) 406 | 407 | * Fix exception handling in `AFJSONEncode` and `AFJSONDecode` (David Keegan) 408 | 409 | * Fix `NSData` initialization with string in `AFBase64EncodedStringFromString` 410 | (Adam Ernst, Mattt Thompson) 411 | 412 | * Fix error check in `appendPartWithFileURL:name:error:` (Warren Moore, 413 | Baldoph, Mattt Thompson) 414 | 415 | * Fix compiler warnings for certain configurations (Charlie Williams) 416 | 417 | * Fix bug caused by passing zero-length `responseData` to response object 418 | initializers (Mattt Thompson, Serge Paquet) -------------------------------------------------------------------------------- /AFNetworking/AFURLConnectionOperation.h: -------------------------------------------------------------------------------- 1 | // AFURLConnectionOperation.h 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #import 26 | 27 | /** 28 | `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. 29 | 30 | ## Subclassing Notes 31 | 32 | 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. 33 | 34 | If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. 35 | 36 | ## NSURLConnection Delegate Methods 37 | 38 | `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: 39 | 40 | - `connection:didReceiveResponse:` 41 | - `connection:didReceiveData:` 42 | - `connectionDidFinishLoading:` 43 | - `connection:didFailWithError:` 44 | - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` 45 | - `connection:willCacheResponse:` 46 | - `connection:canAuthenticateAgainstProtectionSpace:` 47 | - `connection:didReceiveAuthenticationChallenge:` 48 | 49 | If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. 50 | 51 | ## Class Constructors 52 | 53 | Class constructors, or methods that return an unowned 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`. 54 | 55 | ## Callbacks and Completion Blocks 56 | 57 | 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` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. 58 | 59 | Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). 60 | 61 | ## NSCoding & NSCopying Conformance 62 | 63 | `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: 64 | 65 | ### NSCoding Caveats 66 | 67 | - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. 68 | - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. 69 | 70 | ### NSCopying Caveats 71 | 72 | - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. 73 | - A copy of an operation will not include the `outputStream` of the original. 74 | - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. 75 | */ 76 | @interface AFURLConnectionOperation : NSOperation 77 | 78 | ///------------------------------- 79 | /// @name Accessing Run Loop Modes 80 | ///------------------------------- 81 | 82 | /** 83 | The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. 84 | */ 85 | @property (nonatomic, strong) NSSet *runLoopModes; 86 | 87 | ///----------------------------------------- 88 | /// @name Getting URL Connection Information 89 | ///----------------------------------------- 90 | 91 | /** 92 | The request used by the operation's connection. 93 | */ 94 | @property (readonly, nonatomic, strong) NSURLRequest *request; 95 | 96 | /** 97 | The last response received by the operation's connection. 98 | */ 99 | @property (readonly, nonatomic, strong) NSURLResponse *response; 100 | 101 | /** 102 | The error, if any, that occurred in the lifecycle of the request. 103 | */ 104 | @property (readonly, nonatomic, strong) NSError *error; 105 | 106 | ///---------------------------- 107 | /// @name Getting Response Data 108 | ///---------------------------- 109 | 110 | /** 111 | The data received during the request. 112 | */ 113 | @property (readonly, nonatomic, strong) NSData *responseData; 114 | 115 | /** 116 | The string representation of the response data. 117 | 118 | @discussion This method uses the string encoding of the response, or if UTF-8 if not specified, to construct a string from the response data. 119 | */ 120 | @property (readonly, nonatomic, copy) NSString *responseString; 121 | 122 | ///------------------------ 123 | /// @name Accessing Streams 124 | ///------------------------ 125 | 126 | /** 127 | The input stream used to read data to be sent during the request. 128 | 129 | @discussion This property acts as a proxy to the `HTTPBodyStream` property of `request`. 130 | */ 131 | @property (nonatomic, strong) NSInputStream *inputStream; 132 | 133 | /** 134 | The output stream that is used to write data received until the request is finished. 135 | 136 | @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`. The output stream will be scheduled in the network thread runloop upon being set. 137 | */ 138 | @property (nonatomic, strong) NSOutputStream *outputStream; 139 | 140 | ///------------------------------------------------------ 141 | /// @name Initializing an AFURLConnectionOperation Object 142 | ///------------------------------------------------------ 143 | 144 | /** 145 | Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. 146 | 147 | @param urlRequest The request object to be used by the operation connection. 148 | 149 | @discussion This is the designated initializer. 150 | */ 151 | - (id)initWithRequest:(NSURLRequest *)urlRequest; 152 | 153 | ///---------------------------------- 154 | /// @name Pausing / Resuming Requests 155 | ///---------------------------------- 156 | 157 | /** 158 | Pauses the execution of the request operation. 159 | 160 | @discussion A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. 161 | */ 162 | - (void)pause; 163 | 164 | /** 165 | Whether the request operation is currently paused. 166 | 167 | @return `YES` if the operation is currently paused, otherwise `NO`. 168 | */ 169 | - (BOOL)isPaused; 170 | 171 | /** 172 | Resumes the execution of the paused request operation. 173 | 174 | @discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. 175 | */ 176 | - (void)resume; 177 | 178 | ///---------------------------------------------- 179 | /// @name Configuring Backgrounding Task Behavior 180 | ///---------------------------------------------- 181 | 182 | /** 183 | Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. 184 | 185 | @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. 186 | */ 187 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 188 | - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; 189 | #endif 190 | 191 | ///--------------------------------- 192 | /// @name Setting Progress Callbacks 193 | ///--------------------------------- 194 | 195 | /** 196 | Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. 197 | 198 | @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 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, and will execute on the main thread. 199 | */ 200 | - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; 201 | 202 | /** 203 | Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. 204 | 205 | @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 read since the last time the download 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, and will execute on the main thread. 206 | */ 207 | - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; 208 | 209 | ///------------------------------------------------- 210 | /// @name Setting NSURLConnection Delegate Callbacks 211 | ///------------------------------------------------- 212 | 213 | /** 214 | Sets a block to be executed to determine whether the connection should be able to respond to a protection space's form of authentication, as handled by the `NSURLConnectionDelegate` method `connection:canAuthenticateAgainstProtectionSpace:`. 215 | 216 | @param block A block object to be executed to determine whether the connection should be able to respond to a protection space's form of authentication. The block has a `BOOL` return type and takes two arguments: the URL connection object, and the protection space to authenticate against. 217 | 218 | @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:canAuthenticateAgainstProtectionSpace:` will accept invalid SSL certificates, returning `YES` if the protection space authentication method is `NSURLAuthenticationMethodServerTrust`. 219 | */ 220 | - (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace))block; 221 | 222 | /** 223 | Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:didReceiveAuthenticationChallenge:`. 224 | 225 | @param block A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. 226 | 227 | @discussion If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is defined, `connection:didReceiveAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. 228 | */ 229 | - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; 230 | 231 | /** 232 | Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`. 233 | 234 | @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. 235 | */ 236 | - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; 237 | 238 | 239 | /** 240 | Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. 241 | 242 | @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. 243 | */ 244 | - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; 245 | 246 | @end 247 | 248 | ///---------------- 249 | /// @name Constants 250 | ///---------------- 251 | 252 | /** 253 | ## User info dictionary keys 254 | 255 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 256 | 257 | - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` 258 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 259 | 260 | ### Constants 261 | 262 | `AFNetworkingOperationFailingURLRequestErrorKey` 263 | The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. 264 | 265 | `AFNetworkingOperationFailingURLResponseErrorKey` 266 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. 267 | 268 | ## Error Domains 269 | 270 | The following error domain is predefined. 271 | 272 | - `NSString * const AFNetworkingErrorDomain` 273 | 274 | ### Constants 275 | 276 | `AFNetworkingErrorDomain` 277 | AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`. 278 | */ 279 | extern NSString * const AFNetworkingErrorDomain; 280 | extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; 281 | extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 282 | 283 | ///-------------------- 284 | /// @name Notifications 285 | ///-------------------- 286 | 287 | /** 288 | Posted when an operation begins executing. 289 | */ 290 | extern NSString * const AFNetworkingOperationDidStartNotification; 291 | 292 | /** 293 | Posted when an operation finishes. 294 | */ 295 | extern NSString * const AFNetworkingOperationDidFinishNotification; 296 | -------------------------------------------------------------------------------- /Example/AFNetworking Mac Example.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | F8129C001591061B009BFE23 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8129BFF1591061B009BFE23 /* Cocoa.framework */; }; 11 | F8129C321591073C009BFE23 /* AFAppDotNetAPIClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C251591073C009BFE23 /* AFAppDotNetAPIClient.m */; }; 12 | F8129C341591073C009BFE23 /* Post.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C2B1591073C009BFE23 /* Post.m */; }; 13 | F8129C351591073C009BFE23 /* User.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C2D1591073C009BFE23 /* User.m */; }; 14 | F8129C6F15910B15009BFE23 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C6E15910B15009BFE23 /* main.m */; }; 15 | F8129C7115910B3E009BFE23 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = F8129C7015910B3E009BFE23 /* MainMenu.xib */; }; 16 | F8129C7715910C40009BFE23 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = F8129C7515910C40009BFE23 /* AppDelegate.m */; }; 17 | F82EB07C159A172000B10B56 /* AFHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB06E159A172000B10B56 /* AFHTTPClient.m */; }; 18 | F82EB07D159A172000B10B56 /* AFHTTPRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */; }; 19 | F82EB07E159A172000B10B56 /* AFImageRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB072159A172000B10B56 /* AFImageRequestOperation.m */; }; 20 | F82EB07F159A172000B10B56 /* AFJSONRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */; }; 21 | F82EB080159A172000B10B56 /* AFPropertyListRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */; }; 22 | F82EB081159A172000B10B56 /* AFURLConnectionOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */; }; 23 | F82EB082159A172000B10B56 /* AFXMLRequestOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */; }; 24 | F8A847CF161F55A500940F39 /* CoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8A847CE161F55A500940F39 /* CoreServices.framework */; }; 25 | F8A847D2161F55AC00940F39 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F8A847D1161F55AC00940F39 /* SystemConfiguration.framework */; }; 26 | /* End PBXBuildFile section */ 27 | 28 | /* Begin PBXFileReference section */ 29 | F8129BFB1591061B009BFE23 /* AFNetworking Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AFNetworking Example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 30 | F8129BFF1591061B009BFE23 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 31 | F8129C021591061B009BFE23 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = System/Library/Frameworks/AppKit.framework; sourceTree = SDKROOT; }; 32 | F8129C031591061B009BFE23 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = System/Library/Frameworks/CoreData.framework; sourceTree = SDKROOT; }; 33 | F8129C041591061B009BFE23 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 34 | F8129C251591073C009BFE23 /* AFAppDotNetAPIClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFAppDotNetAPIClient.m; path = Classes/AFAppDotNetAPIClient.m; sourceTree = SOURCE_ROOT; }; 35 | F8129C2A1591073C009BFE23 /* Post.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Post.h; sourceTree = ""; }; 36 | F8129C2B1591073C009BFE23 /* Post.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Post.m; sourceTree = ""; }; 37 | F8129C2C1591073C009BFE23 /* User.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = User.h; sourceTree = ""; }; 38 | F8129C2D1591073C009BFE23 /* User.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = User.m; sourceTree = ""; }; 39 | F8129C311591073C009BFE23 /* AFAppDotNetAPIClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFAppDotNetAPIClient.h; path = Classes/AFAppDotNetAPIClient.h; sourceTree = SOURCE_ROOT; }; 40 | F8129C6E15910B15009BFE23 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = SOURCE_ROOT; }; 41 | F8129C7015910B3E009BFE23 /* MainMenu.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = MainMenu.xib; sourceTree = SOURCE_ROOT; }; 42 | F8129C7515910C40009BFE23 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = SOURCE_ROOT; }; 43 | F8129C7615910C40009BFE23 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = SOURCE_ROOT; }; 44 | F82EB06D159A172000B10B56 /* AFHTTPClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPClient.h; path = ../AFNetworking/AFHTTPClient.h; sourceTree = ""; }; 45 | F82EB06E159A172000B10B56 /* AFHTTPClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPClient.m; path = ../AFNetworking/AFHTTPClient.m; sourceTree = ""; }; 46 | F82EB06F159A172000B10B56 /* AFHTTPRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFHTTPRequestOperation.h; path = ../AFNetworking/AFHTTPRequestOperation.h; sourceTree = ""; }; 47 | F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFHTTPRequestOperation.m; path = ../AFNetworking/AFHTTPRequestOperation.m; sourceTree = ""; }; 48 | F82EB071159A172000B10B56 /* AFImageRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFImageRequestOperation.h; path = ../AFNetworking/AFImageRequestOperation.h; sourceTree = ""; }; 49 | F82EB072159A172000B10B56 /* AFImageRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFImageRequestOperation.m; path = ../AFNetworking/AFImageRequestOperation.m; sourceTree = ""; }; 50 | F82EB073159A172000B10B56 /* AFJSONRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFJSONRequestOperation.h; path = ../AFNetworking/AFJSONRequestOperation.h; sourceTree = ""; }; 51 | F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFJSONRequestOperation.m; path = ../AFNetworking/AFJSONRequestOperation.m; sourceTree = ""; }; 52 | F82EB075159A172000B10B56 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = ../AFNetworking/AFNetworking.h; sourceTree = ""; }; 53 | F82EB076159A172000B10B56 /* AFPropertyListRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFPropertyListRequestOperation.h; path = ../AFNetworking/AFPropertyListRequestOperation.h; sourceTree = ""; }; 54 | F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFPropertyListRequestOperation.m; path = ../AFNetworking/AFPropertyListRequestOperation.m; sourceTree = ""; }; 55 | F82EB078159A172000B10B56 /* AFURLConnectionOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFURLConnectionOperation.h; path = ../AFNetworking/AFURLConnectionOperation.h; sourceTree = ""; }; 56 | F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFURLConnectionOperation.m; path = ../AFNetworking/AFURLConnectionOperation.m; sourceTree = ""; }; 57 | F82EB07A159A172000B10B56 /* AFXMLRequestOperation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AFXMLRequestOperation.h; path = ../AFNetworking/AFXMLRequestOperation.h; sourceTree = ""; }; 58 | F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AFXMLRequestOperation.m; path = ../AFNetworking/AFXMLRequestOperation.m; sourceTree = ""; }; 59 | F877018B159A1CE700B45C0D /* AFNetworking Example.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = "AFNetworking Example.entitlements"; sourceTree = ""; }; 60 | F8A847CE161F55A500940F39 /* CoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreServices.framework; path = System/Library/Frameworks/CoreServices.framework; sourceTree = SDKROOT; }; 61 | F8A847D1161F55AC00940F39 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; 62 | /* End PBXFileReference section */ 63 | 64 | /* Begin PBXFrameworksBuildPhase section */ 65 | F8129BF81591061B009BFE23 /* Frameworks */ = { 66 | isa = PBXFrameworksBuildPhase; 67 | buildActionMask = 2147483647; 68 | files = ( 69 | F8A847D2161F55AC00940F39 /* SystemConfiguration.framework in Frameworks */, 70 | F8A847CF161F55A500940F39 /* CoreServices.framework in Frameworks */, 71 | F8129C001591061B009BFE23 /* Cocoa.framework in Frameworks */, 72 | ); 73 | runOnlyForDeploymentPostprocessing = 0; 74 | }; 75 | /* End PBXFrameworksBuildPhase section */ 76 | 77 | /* Begin PBXGroup section */ 78 | F8129BF01591061B009BFE23 = { 79 | isa = PBXGroup; 80 | children = ( 81 | F8A847D1161F55AC00940F39 /* SystemConfiguration.framework */, 82 | F8A847CE161F55A500940F39 /* CoreServices.framework */, 83 | F877018B159A1CE700B45C0D /* AFNetworking Example.entitlements */, 84 | F8129C051591061B009BFE23 /* Classes */, 85 | F8129C4C15910901009BFE23 /* Vendor */, 86 | F8129BFE1591061B009BFE23 /* Frameworks */, 87 | F8129BFC1591061B009BFE23 /* Products */, 88 | ); 89 | sourceTree = ""; 90 | }; 91 | F8129BFC1591061B009BFE23 /* Products */ = { 92 | isa = PBXGroup; 93 | children = ( 94 | F8129BFB1591061B009BFE23 /* AFNetworking Example.app */, 95 | ); 96 | name = Products; 97 | sourceTree = ""; 98 | }; 99 | F8129BFE1591061B009BFE23 /* Frameworks */ = { 100 | isa = PBXGroup; 101 | children = ( 102 | F8129BFF1591061B009BFE23 /* Cocoa.framework */, 103 | F8129C011591061B009BFE23 /* Other Frameworks */, 104 | ); 105 | name = Frameworks; 106 | sourceTree = ""; 107 | }; 108 | F8129C011591061B009BFE23 /* Other Frameworks */ = { 109 | isa = PBXGroup; 110 | children = ( 111 | F8129C021591061B009BFE23 /* AppKit.framework */, 112 | F8129C031591061B009BFE23 /* CoreData.framework */, 113 | F8129C041591061B009BFE23 /* Foundation.framework */, 114 | ); 115 | name = "Other Frameworks"; 116 | sourceTree = ""; 117 | }; 118 | F8129C051591061B009BFE23 /* Classes */ = { 119 | isa = PBXGroup; 120 | children = ( 121 | F8129C311591073C009BFE23 /* AFAppDotNetAPIClient.h */, 122 | F8129C251591073C009BFE23 /* AFAppDotNetAPIClient.m */, 123 | F8129C7615910C40009BFE23 /* AppDelegate.h */, 124 | F8129C7515910C40009BFE23 /* AppDelegate.m */, 125 | F8129C291591073C009BFE23 /* Models */, 126 | F8129C061591061B009BFE23 /* Supporting Files */, 127 | ); 128 | name = Classes; 129 | path = "AFNetworking-Mac-Example"; 130 | sourceTree = ""; 131 | }; 132 | F8129C061591061B009BFE23 /* Supporting Files */ = { 133 | isa = PBXGroup; 134 | children = ( 135 | F8129C6E15910B15009BFE23 /* main.m */, 136 | F8129C7015910B3E009BFE23 /* MainMenu.xib */, 137 | ); 138 | name = "Supporting Files"; 139 | sourceTree = ""; 140 | }; 141 | F8129C291591073C009BFE23 /* Models */ = { 142 | isa = PBXGroup; 143 | children = ( 144 | F8129C2A1591073C009BFE23 /* Post.h */, 145 | F8129C2B1591073C009BFE23 /* Post.m */, 146 | F8129C2C1591073C009BFE23 /* User.h */, 147 | F8129C2D1591073C009BFE23 /* User.m */, 148 | ); 149 | name = Models; 150 | path = Classes/Models; 151 | sourceTree = SOURCE_ROOT; 152 | }; 153 | F8129C4C15910901009BFE23 /* Vendor */ = { 154 | isa = PBXGroup; 155 | children = ( 156 | F82EB083159A172500B10B56 /* AFNetworking */, 157 | ); 158 | name = Vendor; 159 | sourceTree = ""; 160 | }; 161 | F82EB083159A172500B10B56 /* AFNetworking */ = { 162 | isa = PBXGroup; 163 | children = ( 164 | F82EB075159A172000B10B56 /* AFNetworking.h */, 165 | F82EB078159A172000B10B56 /* AFURLConnectionOperation.h */, 166 | F82EB079159A172000B10B56 /* AFURLConnectionOperation.m */, 167 | F82EB06F159A172000B10B56 /* AFHTTPRequestOperation.h */, 168 | F82EB070159A172000B10B56 /* AFHTTPRequestOperation.m */, 169 | F82EB073159A172000B10B56 /* AFJSONRequestOperation.h */, 170 | F82EB074159A172000B10B56 /* AFJSONRequestOperation.m */, 171 | F82EB07A159A172000B10B56 /* AFXMLRequestOperation.h */, 172 | F82EB07B159A172000B10B56 /* AFXMLRequestOperation.m */, 173 | F82EB076159A172000B10B56 /* AFPropertyListRequestOperation.h */, 174 | F82EB077159A172000B10B56 /* AFPropertyListRequestOperation.m */, 175 | F82EB06D159A172000B10B56 /* AFHTTPClient.h */, 176 | F82EB06E159A172000B10B56 /* AFHTTPClient.m */, 177 | F82EB071159A172000B10B56 /* AFImageRequestOperation.h */, 178 | F82EB072159A172000B10B56 /* AFImageRequestOperation.m */, 179 | ); 180 | name = AFNetworking; 181 | sourceTree = ""; 182 | }; 183 | /* End PBXGroup section */ 184 | 185 | /* Begin PBXNativeTarget section */ 186 | F8129BFA1591061B009BFE23 /* AFNetworking Example */ = { 187 | isa = PBXNativeTarget; 188 | buildConfigurationList = F8129C191591061B009BFE23 /* Build configuration list for PBXNativeTarget "AFNetworking Example" */; 189 | buildPhases = ( 190 | F8129BF71591061B009BFE23 /* Sources */, 191 | F8129BF81591061B009BFE23 /* Frameworks */, 192 | F8129BF91591061B009BFE23 /* Resources */, 193 | ); 194 | buildRules = ( 195 | ); 196 | dependencies = ( 197 | ); 198 | name = "AFNetworking Example"; 199 | productName = "AFNetworking-Mac-Example"; 200 | productReference = F8129BFB1591061B009BFE23 /* AFNetworking Example.app */; 201 | productType = "com.apple.product-type.application"; 202 | }; 203 | /* End PBXNativeTarget section */ 204 | 205 | /* Begin PBXProject section */ 206 | F8129BF21591061B009BFE23 /* Project object */ = { 207 | isa = PBXProject; 208 | attributes = { 209 | LastUpgradeCheck = 0450; 210 | }; 211 | buildConfigurationList = F8129BF51591061B009BFE23 /* Build configuration list for PBXProject "AFNetworking Mac Example" */; 212 | compatibilityVersion = "Xcode 3.2"; 213 | developmentRegion = English; 214 | hasScannedForEncodings = 0; 215 | knownRegions = ( 216 | en, 217 | ); 218 | mainGroup = F8129BF01591061B009BFE23; 219 | productRefGroup = F8129BFC1591061B009BFE23 /* Products */; 220 | projectDirPath = ""; 221 | projectRoot = ""; 222 | targets = ( 223 | F8129BFA1591061B009BFE23 /* AFNetworking Example */, 224 | ); 225 | }; 226 | /* End PBXProject section */ 227 | 228 | /* Begin PBXResourcesBuildPhase section */ 229 | F8129BF91591061B009BFE23 /* Resources */ = { 230 | isa = PBXResourcesBuildPhase; 231 | buildActionMask = 2147483647; 232 | files = ( 233 | F8129C7115910B3E009BFE23 /* MainMenu.xib in Resources */, 234 | ); 235 | runOnlyForDeploymentPostprocessing = 0; 236 | }; 237 | /* End PBXResourcesBuildPhase section */ 238 | 239 | /* Begin PBXSourcesBuildPhase section */ 240 | F8129BF71591061B009BFE23 /* Sources */ = { 241 | isa = PBXSourcesBuildPhase; 242 | buildActionMask = 2147483647; 243 | files = ( 244 | F8129C341591073C009BFE23 /* Post.m in Sources */, 245 | F8129C351591073C009BFE23 /* User.m in Sources */, 246 | F8129C321591073C009BFE23 /* AFAppDotNetAPIClient.m in Sources */, 247 | F8129C6F15910B15009BFE23 /* main.m in Sources */, 248 | F8129C7715910C40009BFE23 /* AppDelegate.m in Sources */, 249 | F82EB07C159A172000B10B56 /* AFHTTPClient.m in Sources */, 250 | F82EB07D159A172000B10B56 /* AFHTTPRequestOperation.m in Sources */, 251 | F82EB07E159A172000B10B56 /* AFImageRequestOperation.m in Sources */, 252 | F82EB07F159A172000B10B56 /* AFJSONRequestOperation.m in Sources */, 253 | F82EB080159A172000B10B56 /* AFPropertyListRequestOperation.m in Sources */, 254 | F82EB081159A172000B10B56 /* AFURLConnectionOperation.m in Sources */, 255 | F82EB082159A172000B10B56 /* AFXMLRequestOperation.m in Sources */, 256 | ); 257 | runOnlyForDeploymentPostprocessing = 0; 258 | }; 259 | /* End PBXSourcesBuildPhase section */ 260 | 261 | /* Begin XCBuildConfiguration section */ 262 | F8129C171591061B009BFE23 /* Debug */ = { 263 | isa = XCBuildConfiguration; 264 | buildSettings = { 265 | ALWAYS_SEARCH_USER_PATHS = NO; 266 | ARCHS = "$(ARCHS_STANDARD_64_BIT)"; 267 | CLANG_ENABLE_OBJC_ARC = YES; 268 | COPY_PHASE_STRIP = NO; 269 | GCC_C_LANGUAGE_STANDARD = gnu99; 270 | GCC_DYNAMIC_NO_PIC = NO; 271 | GCC_ENABLE_OBJC_EXCEPTIONS = YES; 272 | GCC_OPTIMIZATION_LEVEL = 0; 273 | GCC_PREPROCESSOR_DEFINITIONS = ( 274 | "DEBUG=1", 275 | "$(inherited)", 276 | ); 277 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 278 | GCC_VERSION = com.apple.compilers.llvm.clang.1_0; 279 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 280 | GCC_WARN_ABOUT_RETURN_TYPE = YES; 281 | GCC_WARN_UNINITIALIZED_AUTOS = YES; 282 | GCC_WARN_UNUSED_VARIABLE = YES; 283 | MACOSX_DEPLOYMENT_TARGET = 10.7; 284 | ONLY_ACTIVE_ARCH = YES; 285 | SDKROOT = macosx; 286 | }; 287 | name = Debug; 288 | }; 289 | F8129C181591061B009BFE23 /* Release */ = { 290 | isa = XCBuildConfiguration; 291 | buildSettings = { 292 | ALWAYS_SEARCH_USER_PATHS = NO; 293 | ARCHS = "$(ARCHS_STANDARD_64_BIT)"; 294 | CLANG_ENABLE_OBJC_ARC = YES; 295 | COPY_PHASE_STRIP = YES; 296 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 297 | GCC_C_LANGUAGE_STANDARD = gnu99; 298 | GCC_ENABLE_OBJC_EXCEPTIONS = YES; 299 | GCC_VERSION = com.apple.compilers.llvm.clang.1_0; 300 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 301 | GCC_WARN_ABOUT_RETURN_TYPE = YES; 302 | GCC_WARN_UNINITIALIZED_AUTOS = YES; 303 | GCC_WARN_UNUSED_VARIABLE = YES; 304 | MACOSX_DEPLOYMENT_TARGET = 10.7; 305 | SDKROOT = macosx; 306 | }; 307 | name = Release; 308 | }; 309 | F8129C1A1591061B009BFE23 /* Debug */ = { 310 | isa = XCBuildConfiguration; 311 | buildSettings = { 312 | CODE_SIGN_ENTITLEMENTS = "AFNetworking Example.entitlements"; 313 | CODE_SIGN_IDENTITY = "Mac Developer"; 314 | COMBINE_HIDPI_IMAGES = YES; 315 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 316 | GCC_PREFIX_HEADER = Prefix.pch; 317 | INFOPLIST_FILE = "Mac-Info.plist"; 318 | PRODUCT_NAME = "$(TARGET_NAME)"; 319 | WRAPPER_EXTENSION = app; 320 | }; 321 | name = Debug; 322 | }; 323 | F8129C1B1591061B009BFE23 /* Release */ = { 324 | isa = XCBuildConfiguration; 325 | buildSettings = { 326 | CODE_SIGN_ENTITLEMENTS = "AFNetworking Example.entitlements"; 327 | CODE_SIGN_IDENTITY = "Mac Developer"; 328 | COMBINE_HIDPI_IMAGES = YES; 329 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 330 | GCC_PREFIX_HEADER = Prefix.pch; 331 | INFOPLIST_FILE = "Mac-Info.plist"; 332 | PRODUCT_NAME = "$(TARGET_NAME)"; 333 | WRAPPER_EXTENSION = app; 334 | }; 335 | name = Release; 336 | }; 337 | /* End XCBuildConfiguration section */ 338 | 339 | /* Begin XCConfigurationList section */ 340 | F8129BF51591061B009BFE23 /* Build configuration list for PBXProject "AFNetworking Mac Example" */ = { 341 | isa = XCConfigurationList; 342 | buildConfigurations = ( 343 | F8129C171591061B009BFE23 /* Debug */, 344 | F8129C181591061B009BFE23 /* Release */, 345 | ); 346 | defaultConfigurationIsVisible = 0; 347 | defaultConfigurationName = Release; 348 | }; 349 | F8129C191591061B009BFE23 /* Build configuration list for PBXNativeTarget "AFNetworking Example" */ = { 350 | isa = XCConfigurationList; 351 | buildConfigurations = ( 352 | F8129C1A1591061B009BFE23 /* Debug */, 353 | F8129C1B1591061B009BFE23 /* Release */, 354 | ); 355 | defaultConfigurationIsVisible = 0; 356 | defaultConfigurationName = Release; 357 | }; 358 | /* End XCConfigurationList section */ 359 | }; 360 | rootObject = F8129BF21591061B009BFE23 /* Project object */; 361 | } 362 | -------------------------------------------------------------------------------- /AFNetworking/AFURLConnectionOperation.m: -------------------------------------------------------------------------------- 1 | // AFURLConnectionOperation.m 2 | // 3 | // Copyright (c) 2011 Gowalla (http://gowalla.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import "AFURLConnectionOperation.h" 24 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 25 | #import 26 | #endif 27 | 28 | #if !__has_feature(objc_arc) 29 | #error AFNetworking must be built with ARC. 30 | // You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. 31 | #endif 32 | 33 | typedef enum { 34 | AFOperationPausedState = -1, 35 | AFOperationReadyState = 1, 36 | AFOperationExecutingState = 2, 37 | AFOperationFinishedState = 3, 38 | } _AFOperationState; 39 | 40 | typedef signed short AFOperationState; 41 | 42 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 43 | typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; 44 | #else 45 | typedef id AFBackgroundTaskIdentifier; 46 | #endif 47 | 48 | static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; 49 | 50 | NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain"; 51 | NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey"; 52 | NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey"; 53 | 54 | NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; 55 | NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; 56 | 57 | typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); 58 | typedef BOOL (^AFURLConnectionOperationAuthenticationAgainstProtectionSpaceBlock)(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace); 59 | typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); 60 | typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); 61 | typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); 62 | 63 | static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { 64 | switch (state) { 65 | case AFOperationReadyState: 66 | return @"isReady"; 67 | case AFOperationExecutingState: 68 | return @"isExecuting"; 69 | case AFOperationFinishedState: 70 | return @"isFinished"; 71 | case AFOperationPausedState: 72 | return @"isPaused"; 73 | default: 74 | return @"state"; 75 | } 76 | } 77 | 78 | static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { 79 | switch (fromState) { 80 | case AFOperationReadyState: 81 | switch (toState) { 82 | case AFOperationPausedState: 83 | case AFOperationExecutingState: 84 | return YES; 85 | case AFOperationFinishedState: 86 | return isCancelled; 87 | default: 88 | return NO; 89 | } 90 | case AFOperationExecutingState: 91 | switch (toState) { 92 | case AFOperationPausedState: 93 | case AFOperationFinishedState: 94 | return YES; 95 | default: 96 | return NO; 97 | } 98 | case AFOperationFinishedState: 99 | return NO; 100 | case AFOperationPausedState: 101 | return toState == AFOperationReadyState; 102 | default: 103 | return YES; 104 | } 105 | } 106 | 107 | @interface AFURLConnectionOperation () 108 | @property (readwrite, nonatomic, assign) AFOperationState state; 109 | @property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; 110 | @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; 111 | @property (readwrite, nonatomic, strong) NSURLConnection *connection; 112 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 113 | @property (readwrite, nonatomic, strong) NSURLResponse *response; 114 | @property (readwrite, nonatomic, strong) NSError *error; 115 | @property (readwrite, nonatomic, strong) NSData *responseData; 116 | @property (readwrite, nonatomic, copy) NSString *responseString; 117 | @property (readwrite, nonatomic, assign) long long totalBytesRead; 118 | @property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; 119 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; 120 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; 121 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationAgainstProtectionSpaceBlock authenticationAgainstProtectionSpace; 122 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; 123 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; 124 | @property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; 125 | 126 | - (void)operationDidStart; 127 | - (void)finish; 128 | - (void)cancelConnection; 129 | @end 130 | 131 | @implementation AFURLConnectionOperation 132 | @synthesize state = _state; 133 | @synthesize cancelled = _cancelled; 134 | @synthesize connection = _connection; 135 | @synthesize runLoopModes = _runLoopModes; 136 | @synthesize request = _request; 137 | @synthesize response = _response; 138 | @synthesize error = _error; 139 | @synthesize responseData = _responseData; 140 | @synthesize responseString = _responseString; 141 | @synthesize totalBytesRead = _totalBytesRead; 142 | @dynamic inputStream; 143 | @synthesize outputStream = _outputStream; 144 | @synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier; 145 | @synthesize uploadProgress = _uploadProgress; 146 | @synthesize downloadProgress = _downloadProgress; 147 | @synthesize authenticationAgainstProtectionSpace = _authenticationAgainstProtectionSpace; 148 | @synthesize authenticationChallenge = _authenticationChallenge; 149 | @synthesize cacheResponse = _cacheResponse; 150 | @synthesize redirectResponse = _redirectResponse; 151 | @synthesize lock = _lock; 152 | 153 | + (void) __attribute__((noreturn)) networkRequestThreadEntryPoint:(id)__unused object { 154 | do { 155 | @autoreleasepool { 156 | [[NSRunLoop currentRunLoop] run]; 157 | } 158 | } while (YES); 159 | } 160 | 161 | + (NSThread *)networkRequestThread { 162 | static NSThread *_networkRequestThread = nil; 163 | static dispatch_once_t oncePredicate; 164 | 165 | dispatch_once(&oncePredicate, ^{ 166 | _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; 167 | [_networkRequestThread start]; 168 | }); 169 | 170 | return _networkRequestThread; 171 | } 172 | 173 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 174 | self = [super init]; 175 | if (!self) { 176 | return nil; 177 | } 178 | 179 | self.lock = [[NSRecursiveLock alloc] init]; 180 | self.lock.name = kAFNetworkingLockName; 181 | 182 | self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; 183 | 184 | self.request = urlRequest; 185 | 186 | self.outputStream = [NSOutputStream outputStreamToMemory]; 187 | NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 188 | for (NSString *runLoopMode in self.runLoopModes) { 189 | [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; 190 | } 191 | 192 | self.state = AFOperationReadyState; 193 | 194 | return self; 195 | } 196 | 197 | - (void)dealloc { 198 | if (_outputStream) { 199 | [_outputStream close]; 200 | _outputStream = nil; 201 | } 202 | 203 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 204 | if (_backgroundTaskIdentifier) { 205 | [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; 206 | _backgroundTaskIdentifier = UIBackgroundTaskInvalid; 207 | } 208 | #endif 209 | } 210 | 211 | - (NSString *)description { 212 | return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; 213 | } 214 | 215 | - (void)setCompletionBlock:(void (^)(void))block { 216 | [self.lock lock]; 217 | if (!block) { 218 | [super setCompletionBlock:nil]; 219 | } else { 220 | __unsafe_unretained id _blockSelf = self; 221 | [super setCompletionBlock:^ { 222 | block(); 223 | [_blockSelf setCompletionBlock:nil]; 224 | }]; 225 | } 226 | [self.lock unlock]; 227 | } 228 | 229 | - (NSInputStream *)inputStream { 230 | return self.request.HTTPBodyStream; 231 | } 232 | 233 | - (void)setInputStream:(NSInputStream *)inputStream { 234 | [self willChangeValueForKey:@"inputStream"]; 235 | NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; 236 | mutableRequest.HTTPBodyStream = inputStream; 237 | self.request = mutableRequest; 238 | [self didChangeValueForKey:@"inputStream"]; 239 | } 240 | 241 | - (void)setOutputStream:(NSOutputStream *)outputStream { 242 | if (outputStream == _outputStream) { 243 | return; 244 | } 245 | 246 | [self willChangeValueForKey:@"outputStream"]; 247 | 248 | if (_outputStream) { 249 | [_outputStream close]; 250 | } 251 | _outputStream = outputStream; 252 | [self didChangeValueForKey:@"outputStream"]; 253 | } 254 | 255 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 256 | - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { 257 | [self.lock lock]; 258 | if (!self.backgroundTaskIdentifier) { 259 | UIApplication *application = [UIApplication sharedApplication]; 260 | self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ 261 | if (handler) { 262 | handler(); 263 | } 264 | 265 | [self cancel]; 266 | 267 | [application endBackgroundTask:self.backgroundTaskIdentifier]; 268 | self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; 269 | }]; 270 | } 271 | [self.lock unlock]; 272 | } 273 | #endif 274 | 275 | - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { 276 | self.uploadProgress = block; 277 | } 278 | 279 | - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { 280 | self.downloadProgress = block; 281 | } 282 | 283 | - (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL (^)(NSURLConnection *, NSURLProtectionSpace *))block { 284 | self.authenticationAgainstProtectionSpace = block; 285 | } 286 | 287 | - (void)setAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { 288 | self.authenticationChallenge = block; 289 | } 290 | 291 | - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { 292 | self.cacheResponse = block; 293 | } 294 | 295 | - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { 296 | self.redirectResponse = block; 297 | } 298 | 299 | - (void)setState:(AFOperationState)state { 300 | [self.lock lock]; 301 | if (AFStateTransitionIsValid(self.state, state, [self isCancelled])) { 302 | NSString *oldStateKey = AFKeyPathFromOperationState(self.state); 303 | NSString *newStateKey = AFKeyPathFromOperationState(state); 304 | 305 | [self willChangeValueForKey:newStateKey]; 306 | [self willChangeValueForKey:oldStateKey]; 307 | _state = state; 308 | [self didChangeValueForKey:oldStateKey]; 309 | [self didChangeValueForKey:newStateKey]; 310 | 311 | switch (state) { 312 | case AFOperationExecutingState: 313 | [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; 314 | break; 315 | case AFOperationFinishedState: 316 | [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; 317 | break; 318 | default: 319 | break; 320 | } 321 | } 322 | [self.lock unlock]; 323 | } 324 | 325 | - (NSString *)responseString { 326 | [self.lock lock]; 327 | if (!_responseString && self.response && self.responseData) { 328 | NSStringEncoding textEncoding = NSUTF8StringEncoding; 329 | if (self.response.textEncodingName) { 330 | textEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName)); 331 | } 332 | 333 | self.responseString = [[NSString alloc] initWithData:self.responseData encoding:textEncoding]; 334 | } 335 | [self.lock unlock]; 336 | 337 | return _responseString; 338 | } 339 | 340 | - (void)pause { 341 | if ([self isPaused] || [self isFinished] || [self isCancelled]) { 342 | return; 343 | } 344 | 345 | [self.lock lock]; 346 | 347 | if ([self isExecuting]) { 348 | [self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; 349 | [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; 350 | } 351 | 352 | self.state = AFOperationPausedState; 353 | 354 | [self.lock unlock]; 355 | } 356 | 357 | - (BOOL)isPaused { 358 | return self.state == AFOperationPausedState; 359 | } 360 | 361 | - (void)resume { 362 | if (![self isPaused]) { 363 | return; 364 | } 365 | 366 | [self.lock lock]; 367 | self.state = AFOperationReadyState; 368 | 369 | [self start]; 370 | [self.lock unlock]; 371 | } 372 | 373 | #pragma mark - NSOperation 374 | 375 | - (BOOL)isReady { 376 | return self.state == AFOperationReadyState && [super isReady]; 377 | } 378 | 379 | - (BOOL)isExecuting { 380 | return self.state == AFOperationExecutingState; 381 | } 382 | 383 | - (BOOL)isFinished { 384 | return self.state == AFOperationFinishedState; 385 | } 386 | 387 | - (BOOL)isConcurrent { 388 | return YES; 389 | } 390 | 391 | - (void)start { 392 | [self.lock lock]; 393 | if ([self isReady]) { 394 | self.state = AFOperationExecutingState; 395 | 396 | [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; 397 | } 398 | [self.lock unlock]; 399 | } 400 | 401 | - (void)operationDidStart { 402 | [self.lock lock]; 403 | if ([self isCancelled]) { 404 | [self finish]; 405 | } else { 406 | self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; 407 | 408 | NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 409 | for (NSString *runLoopMode in self.runLoopModes) { 410 | [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; 411 | [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; 412 | } 413 | 414 | [self.connection start]; 415 | } 416 | [self.lock unlock]; 417 | } 418 | 419 | - (void)finish { 420 | self.state = AFOperationFinishedState; 421 | } 422 | 423 | - (void)cancel { 424 | [self.lock lock]; 425 | if (![self isFinished] && ![self isCancelled]) { 426 | [self willChangeValueForKey:@"isCancelled"]; 427 | _cancelled = YES; 428 | [super cancel]; 429 | [self didChangeValueForKey:@"isCancelled"]; 430 | 431 | // Cancel the connection on the thread it runs on to prevent race conditions 432 | [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; 433 | } 434 | [self.lock unlock]; 435 | } 436 | 437 | - (void)cancelConnection { 438 | if (self.connection) { 439 | [self.connection cancel]; 440 | 441 | // Manually send this delegate message since `[self.connection cancel]` causes the connection to never send another message to its delegate 442 | NSDictionary *userInfo = nil; 443 | if ([self.request URL]) { 444 | userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; 445 | } 446 | [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]]; 447 | } 448 | } 449 | 450 | #pragma mark - NSURLConnectionDelegate 451 | 452 | - (BOOL)connection:(NSURLConnection *)connection 453 | canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 454 | { 455 | #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 456 | if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 457 | return YES; 458 | } 459 | #endif 460 | 461 | if (self.authenticationAgainstProtectionSpace) { 462 | return self.authenticationAgainstProtectionSpace(connection, protectionSpace); 463 | } else if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] || [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) { 464 | return NO; 465 | } else { 466 | return YES; 467 | } 468 | } 469 | 470 | - (void)connection:(NSURLConnection *)connection 471 | didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 472 | { 473 | #ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 474 | if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 475 | [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; 476 | return; 477 | } 478 | #endif 479 | 480 | if (self.authenticationChallenge) { 481 | self.authenticationChallenge(connection, challenge); 482 | } else { 483 | if ([challenge previousFailureCount] == 0) { 484 | NSURLCredential *credential = nil; 485 | 486 | NSString *username = (__bridge_transfer NSString *)CFURLCopyUserName((__bridge CFURLRef)[self.request URL]); 487 | NSString *password = (__bridge_transfer NSString *)CFURLCopyPassword((__bridge CFURLRef)[self.request URL]); 488 | 489 | if (username && password) { 490 | credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone]; 491 | } else if (username) { 492 | credential = [[[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:[challenge protectionSpace]] objectForKey:username]; 493 | } else { 494 | credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[challenge protectionSpace]]; 495 | } 496 | 497 | if (credential) { 498 | [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 499 | } else { 500 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 501 | } 502 | } else { 503 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 504 | } 505 | } 506 | } 507 | 508 | - (NSURLRequest *)connection:(NSURLConnection *)connection 509 | willSendRequest:(NSURLRequest *)request 510 | redirectResponse:(NSURLResponse *)redirectResponse 511 | { 512 | if (self.redirectResponse) { 513 | return self.redirectResponse(connection, request, redirectResponse); 514 | } else { 515 | return request; 516 | } 517 | } 518 | 519 | - (void)connection:(NSURLConnection *)__unused connection 520 | didSendBodyData:(NSInteger)bytesWritten 521 | totalBytesWritten:(NSInteger)totalBytesWritten 522 | totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite 523 | { 524 | if (self.uploadProgress) { 525 | dispatch_async(dispatch_get_main_queue(), ^{ 526 | self.uploadProgress(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); 527 | }); 528 | } 529 | } 530 | 531 | - (void)connection:(NSURLConnection *)__unused connection 532 | didReceiveResponse:(NSURLResponse *)response 533 | { 534 | self.response = response; 535 | 536 | [self.outputStream open]; 537 | } 538 | 539 | - (void)connection:(NSURLConnection *)__unused connection 540 | didReceiveData:(NSData *)data 541 | { 542 | self.totalBytesRead += [data length]; 543 | 544 | if ([self.outputStream hasSpaceAvailable]) { 545 | const uint8_t *dataBuffer = (uint8_t *) [data bytes]; 546 | [self.outputStream write:&dataBuffer[0] maxLength:[data length]]; 547 | } 548 | 549 | if (self.downloadProgress) { 550 | dispatch_async(dispatch_get_main_queue(), ^{ 551 | self.downloadProgress([data length], self.totalBytesRead, self.response.expectedContentLength); 552 | }); 553 | } 554 | } 555 | 556 | - (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection { 557 | self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; 558 | 559 | [self.outputStream close]; 560 | 561 | [self finish]; 562 | 563 | self.connection = nil; 564 | } 565 | 566 | - (void)connection:(NSURLConnection *)__unused connection 567 | didFailWithError:(NSError *)error 568 | { 569 | self.error = error; 570 | 571 | [self.outputStream close]; 572 | 573 | [self finish]; 574 | 575 | self.connection = nil; 576 | } 577 | 578 | - (NSCachedURLResponse *)connection:(NSURLConnection *)connection 579 | willCacheResponse:(NSCachedURLResponse *)cachedResponse 580 | { 581 | if (self.cacheResponse) { 582 | return self.cacheResponse(connection, cachedResponse); 583 | } else { 584 | if ([self isCancelled]) { 585 | return nil; 586 | } 587 | 588 | return cachedResponse; 589 | } 590 | } 591 | 592 | #pragma mark - NSCoding 593 | 594 | - (id)initWithCoder:(NSCoder *)aDecoder { 595 | NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"]; 596 | 597 | self = [self initWithRequest:request]; 598 | if (!self) { 599 | return nil; 600 | } 601 | 602 | self.state = [aDecoder decodeIntegerForKey:@"state"]; 603 | self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"]; 604 | self.response = [aDecoder decodeObjectForKey:@"response"]; 605 | self.error = [aDecoder decodeObjectForKey:@"error"]; 606 | self.responseData = [aDecoder decodeObjectForKey:@"responseData"]; 607 | self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue]; 608 | 609 | return self; 610 | } 611 | 612 | - (void)encodeWithCoder:(NSCoder *)aCoder { 613 | [self pause]; 614 | 615 | [aCoder encodeObject:self.request forKey:@"request"]; 616 | 617 | switch (self.state) { 618 | case AFOperationExecutingState: 619 | case AFOperationPausedState: 620 | [aCoder encodeInteger:AFOperationReadyState forKey:@"state"]; 621 | break; 622 | default: 623 | [aCoder encodeInteger:self.state forKey:@"state"]; 624 | break; 625 | } 626 | 627 | [aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"]; 628 | [aCoder encodeObject:self.response forKey:@"response"]; 629 | [aCoder encodeObject:self.error forKey:@"error"]; 630 | [aCoder encodeObject:self.responseData forKey:@"responseData"]; 631 | [aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"]; 632 | } 633 | 634 | #pragma mark - NSCopying 635 | 636 | - (id)copyWithZone:(NSZone *)zone { 637 | AFURLConnectionOperation *operation = [[[self class] allocWithZone:zone] initWithRequest:self.request]; 638 | 639 | operation.uploadProgress = self.uploadProgress; 640 | operation.downloadProgress = self.downloadProgress; 641 | operation.authenticationAgainstProtectionSpace = self.authenticationAgainstProtectionSpace; 642 | operation.authenticationChallenge = self.authenticationChallenge; 643 | operation.cacheResponse = self.cacheResponse; 644 | operation.redirectResponse = self.redirectResponse; 645 | 646 | return operation; 647 | } 648 | 649 | @end 650 | --------------------------------------------------------------------------------