├── .gitignore ├── .travis.yml ├── AFNetworking.podspec ├── AFNetworking.xcworkspace └── contents.xcworkspacedata ├── AFNetworking ├── AFHTTPClient.h ├── AFHTTPClient.m ├── AFHTTPRequestOperation.h ├── AFHTTPRequestOperation.m ├── AFImageRequestOperation.h ├── AFImageRequestOperation.m ├── AFJSONRequestOperation.h ├── AFJSONRequestOperation.m ├── AFNetworkActivityIndicatorManager.h ├── AFNetworkActivityIndicatorManager.m ├── AFNetworking.h ├── AFPropertyListRequestOperation.h ├── AFPropertyListRequestOperation.m ├── AFURLConnectionOperation.h ├── AFURLConnectionOperation.m ├── AFXMLRequestOperation.h ├── AFXMLRequestOperation.m ├── UIImageView+AFNetworking.h └── UIImageView+AFNetworking.m ├── CHANGES ├── Example ├── AFNetworking Example.entitlements ├── AFNetworking Mac Example.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── AFNetworking iOS Example.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── AppDelegate.h ├── AppDelegate.m ├── Classes │ ├── AFAppDotNetAPIClient.h │ ├── AFAppDotNetAPIClient.m │ ├── Controllers │ │ ├── GlobalTimelineViewController.h │ │ └── GlobalTimelineViewController.m │ ├── Models │ │ ├── Post.h │ │ ├── Post.m │ │ ├── User.h │ │ └── User.m │ └── Views │ │ ├── PostTableViewCell.h │ │ └── PostTableViewCell.m ├── Default-568h@2x.png ├── Default.png ├── Default@2x.png ├── Icon.png ├── Icon@2x.png ├── Images │ ├── profile-image-placeholder.png │ └── profile-image-placeholder@2x.png ├── Mac-Info.plist ├── MainMenu.xib ├── Prefix.pch ├── adn.cer ├── en.lproj │ └── MainMenu.xib ├── iOS-Info.plist └── main.m ├── LICENSE ├── README.md ├── Rakefile └── Tests ├── AFHTTPClientTests.m ├── AFHTTPRequestOperationTests.m ├── AFImageRequestOperationTests.m ├── AFJSONRequestOperationTests.m ├── AFMockURLProtocol.h ├── AFMockURLProtocol.m ├── AFNetworking Tests.xcodeproj └── project.pbxproj ├── AFNetworking-Prefix.pch ├── AFNetworkingTests-Info.plist ├── AFNetworkingTests.h ├── AFNetworkingTests.m ├── AFURLConnectionOperationTests.m ├── Podfile ├── Podfile.lock ├── Resources ├── ca.cer ├── derived.cert ├── root_certificate.cer └── root_certificate.key └── Schemes ├── OS X Tests.xcscheme └── iOS Tests.xcscheme /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | .DS_Store 3 | build/ 4 | *.pbxuser 5 | !default.pbxuser 6 | *.mode1v3 7 | !default.mode1v3 8 | *.mode2v3 9 | !default.mode2v3 10 | *.perspectivev3 11 | !default.perspectivev3 12 | *.xcworkspace 13 | !default.xcworkspace 14 | xcuserdata 15 | profile 16 | *.moved-aside 17 | DerivedData 18 | .idea/ 19 | Tests/Pods 20 | Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/ 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: objective-c 2 | before_install: 3 | - brew update 4 | - brew uninstall xctool && brew install https://raw.github.com/fpotter/homebrew/246a1439dab49542d4531ad7e1bac7048151f601/Library/Formula/xctool.rb 5 | - gem install cocoapods -v 0.22.2 6 | - cd Tests && pod install && cd $TRAVIS_BUILD_DIR 7 | script: rake test 8 | -------------------------------------------------------------------------------- /AFNetworking.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = 'AFNetworking' 3 | s.version = '1.3.2' 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.3.2' } 9 | s.source_files = 'AFNetworking' 10 | s.requires_arc = true 11 | 12 | s.ios.deployment_target = '5.0' 13 | s.ios.frameworks = 'MobileCoreServices', 'SystemConfiguration', 'Security', 'CoreGraphics' 14 | 15 | s.osx.deployment_target = '10.7' 16 | s.osx.frameworks = 'CoreServices', 'SystemConfiguration', 'Security' 17 | 18 | s.prefix_header_contents = <<-EOS 19 | #import 20 | 21 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 22 | #import 23 | #import 24 | #import 25 | #else 26 | #import 27 | #import 28 | #import 29 | #endif 30 | EOS 31 | end -------------------------------------------------------------------------------- /AFNetworking.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 9 | 10 | 12 | 13 | 15 | 16 | 18 | 19 | 21 | 22 | 24 | 25 | 27 | 28 | 30 | 31 | 33 | 34 | 36 | 37 | 39 | 40 | 42 | 43 | 45 | 46 | 48 | 49 | 51 | 52 | 54 | 55 | 57 | 58 | 60 | 61 | 63 | 64 | 65 | 67 | 68 | 70 | 71 | 73 | 74 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /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 (nonatomic, 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 (nonatomic, 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 | This method should be overridden in subclasses in order to specify the response object passed into the success block. 116 | 117 | @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. 118 | @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. 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/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 | #pragma clang diagnostic push 34 | #pragma clang diagnostic ignored "-Wstrict-selector-match" 35 | 36 | NSSet * AFContentTypesFromHTTPHeader(NSString *string) { 37 | if (!string) { 38 | return nil; 39 | } 40 | 41 | NSArray *mediaRanges = [string componentsSeparatedByString:@","]; 42 | NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count]; 43 | 44 | [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) { 45 | NSRange parametersRange = [mediaRange rangeOfString:@";"]; 46 | if (parametersRange.location != NSNotFound) { 47 | mediaRange = [mediaRange substringToIndex:parametersRange.location]; 48 | } 49 | 50 | mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 51 | 52 | if (mediaRange.length > 0) { 53 | [mutableContentTypes addObject:mediaRange]; 54 | } 55 | }]; 56 | 57 | return [NSSet setWithSet:mutableContentTypes]; 58 | } 59 | 60 | static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) { 61 | if (!string) { 62 | return; 63 | } 64 | 65 | NSScanner *scanner = [NSScanner scannerWithString:string]; 66 | [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 67 | [scanner scanUpToString:@"/" intoString:type]; 68 | [scanner scanString:@"/" intoString:nil]; 69 | [scanner scanUpToString:@";" intoString:subtype]; 70 | } 71 | 72 | static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) { 73 | NSMutableString *string = [NSMutableString string]; 74 | 75 | NSRange range = NSMakeRange([indexSet firstIndex], 1); 76 | while (range.location != NSNotFound) { 77 | NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location]; 78 | while (nextIndex == range.location + range.length) { 79 | range.length++; 80 | nextIndex = [indexSet indexGreaterThanIndex:nextIndex]; 81 | } 82 | 83 | if (string.length) { 84 | [string appendString:@","]; 85 | } 86 | 87 | if (range.length == 1) { 88 | [string appendFormat:@"%lu", (long)range.location]; 89 | } else { 90 | NSUInteger firstIndex = range.location; 91 | NSUInteger lastIndex = firstIndex + range.length - 1; 92 | [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex]; 93 | } 94 | 95 | range.location = nextIndex; 96 | range.length = 1; 97 | } 98 | 99 | return string; 100 | } 101 | 102 | static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) { 103 | Method originalMethod = class_getClassMethod(klass, selector); 104 | IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block); 105 | class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod)); 106 | } 107 | 108 | #pragma mark - 109 | 110 | @interface AFHTTPRequestOperation () 111 | @property (readwrite, nonatomic, strong) NSURLRequest *request; 112 | @property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; 113 | @property (readwrite, nonatomic, strong) NSError *HTTPError; 114 | @end 115 | 116 | @implementation AFHTTPRequestOperation 117 | @synthesize HTTPError = _HTTPError; 118 | @synthesize successCallbackQueue = _successCallbackQueue; 119 | @synthesize failureCallbackQueue = _failureCallbackQueue; 120 | @dynamic request; 121 | @dynamic response; 122 | 123 | - (void)dealloc { 124 | if (_successCallbackQueue) { 125 | #if !OS_OBJECT_USE_OBJC 126 | dispatch_release(_successCallbackQueue); 127 | #endif 128 | _successCallbackQueue = NULL; 129 | } 130 | 131 | if (_failureCallbackQueue) { 132 | #if !OS_OBJECT_USE_OBJC 133 | dispatch_release(_failureCallbackQueue); 134 | #endif 135 | _failureCallbackQueue = NULL; 136 | } 137 | } 138 | 139 | - (NSError *)error { 140 | if (!self.HTTPError && self.response) { 141 | if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) { 142 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; 143 | [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey]; 144 | [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; 145 | [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey]; 146 | [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey]; 147 | 148 | if (![self hasAcceptableStatusCode]) { 149 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 150 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey]; 151 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo]; 152 | } else if (![self hasAcceptableContentType]) { 153 | // Don't invalidate content type if there is no content 154 | if ([self.responseData length] > 0) { 155 | [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; 156 | self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; 157 | } 158 | } 159 | } 160 | } 161 | 162 | if (self.HTTPError) { 163 | return self.HTTPError; 164 | } else { 165 | return [super error]; 166 | } 167 | } 168 | 169 | - (NSStringEncoding)responseStringEncoding { 170 | // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value. 171 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1 172 | if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) { 173 | NSString *type = nil; 174 | AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil); 175 | 176 | if ([type isEqualToString:@"text"]) { 177 | return NSISOLatin1StringEncoding; 178 | } 179 | } 180 | 181 | return [super responseStringEncoding]; 182 | } 183 | 184 | - (void)pause { 185 | unsigned long long offset = 0; 186 | if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { 187 | offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; 188 | } else { 189 | offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; 190 | } 191 | 192 | NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; 193 | if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { 194 | [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; 195 | } 196 | [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; 197 | self.request = mutableURLRequest; 198 | 199 | [super pause]; 200 | } 201 | 202 | - (BOOL)hasAcceptableStatusCode { 203 | if (!self.response) { 204 | return NO; 205 | } 206 | 207 | NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; 208 | return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode]; 209 | } 210 | 211 | - (BOOL)hasAcceptableContentType { 212 | if (!self.response) { 213 | return NO; 214 | } 215 | 216 | // 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". 217 | // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html 218 | NSString *contentType = [self.response MIMEType]; 219 | if (!contentType) { 220 | contentType = @"application/octet-stream"; 221 | } 222 | 223 | return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType]; 224 | } 225 | 226 | - (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue { 227 | if (successCallbackQueue != _successCallbackQueue) { 228 | if (_successCallbackQueue) { 229 | #if !OS_OBJECT_USE_OBJC 230 | dispatch_release(_successCallbackQueue); 231 | #endif 232 | _successCallbackQueue = NULL; 233 | } 234 | 235 | if (successCallbackQueue) { 236 | #if !OS_OBJECT_USE_OBJC 237 | dispatch_retain(successCallbackQueue); 238 | #endif 239 | _successCallbackQueue = successCallbackQueue; 240 | } 241 | } 242 | } 243 | 244 | - (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue { 245 | if (failureCallbackQueue != _failureCallbackQueue) { 246 | if (_failureCallbackQueue) { 247 | #if !OS_OBJECT_USE_OBJC 248 | dispatch_release(_failureCallbackQueue); 249 | #endif 250 | _failureCallbackQueue = NULL; 251 | } 252 | 253 | if (failureCallbackQueue) { 254 | #if !OS_OBJECT_USE_OBJC 255 | dispatch_retain(failureCallbackQueue); 256 | #endif 257 | _failureCallbackQueue = failureCallbackQueue; 258 | } 259 | } 260 | } 261 | 262 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 263 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 264 | { 265 | // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. 266 | #pragma clang diagnostic push 267 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 268 | #pragma clang diagnostic ignored "-Wgnu" 269 | self.completionBlock = ^{ 270 | if (self.error) { 271 | if (failure) { 272 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 273 | failure(self, self.error); 274 | }); 275 | } 276 | } else { 277 | if (success) { 278 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 279 | success(self, self.responseData); 280 | }); 281 | } 282 | } 283 | }; 284 | #pragma clang diagnostic pop 285 | } 286 | 287 | #pragma mark - AFHTTPRequestOperation 288 | 289 | + (NSIndexSet *)acceptableStatusCodes { 290 | return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; 291 | } 292 | 293 | + (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes { 294 | NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]]; 295 | [mutableStatusCodes addIndexes:statusCodes]; 296 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) { 297 | return mutableStatusCodes; 298 | }); 299 | } 300 | 301 | + (NSSet *)acceptableContentTypes { 302 | return nil; 303 | } 304 | 305 | + (void)addAcceptableContentTypes:(NSSet *)contentTypes { 306 | NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES]; 307 | [mutableContentTypes unionSet:contentTypes]; 308 | AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) { 309 | return mutableContentTypes; 310 | }); 311 | } 312 | 313 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 314 | if ([[self class] isEqual:[AFHTTPRequestOperation class]]) { 315 | return YES; 316 | } 317 | 318 | return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])]; 319 | } 320 | 321 | @end 322 | 323 | #pragma clang diagnostic pop 324 | -------------------------------------------------------------------------------- /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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 29 | #import 30 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 31 | #import 32 | #endif 33 | 34 | /** 35 | `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and 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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 58 | @property (readonly, nonatomic, strong) UIImage *responseImage; 59 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 60 | @property (readonly, nonatomic, strong) NSImage *responseImage; 61 | #endif 62 | 63 | #if defined(__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 | 69 | /** 70 | Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. 71 | */ 72 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; 73 | #endif 74 | 75 | /** 76 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 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 request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request. 80 | 81 | @return A new image request operation 82 | */ 83 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 84 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 85 | success:(void (^)(UIImage *image))success; 86 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 87 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 88 | success:(void (^)(NSImage *image))success; 89 | #endif 90 | 91 | /** 92 | Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. 93 | 94 | @param urlRequest The request object to be loaded asynchronously during execution of the operation. 95 | @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. 96 | @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. 97 | @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. 98 | 99 | @return A new image request operation 100 | */ 101 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 102 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 103 | imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock 104 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 105 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 106 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 107 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 108 | imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock 109 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 110 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 111 | #endif 112 | 113 | @end 114 | -------------------------------------------------------------------------------- /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 image_request_operation_processing_queue() { 26 | static dispatch_queue_t af_image_request_operation_processing_queue; 27 | static dispatch_once_t onceToken; 28 | dispatch_once(&onceToken, ^{ 29 | af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT); 30 | }); 31 | 32 | return af_image_request_operation_processing_queue; 33 | } 34 | 35 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 36 | #import 37 | 38 | static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { 39 | if ([UIImage instancesRespondToSelector:@selector(initWithData:scale:)]) { 40 | return [[UIImage alloc] initWithData:data scale:scale]; 41 | } else { 42 | UIImage *image = [[UIImage alloc] initWithData:data]; 43 | return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; 44 | } 45 | } 46 | 47 | static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { 48 | if (!data || [data length] == 0) { 49 | return nil; 50 | } 51 | 52 | CGImageRef imageRef = nil; 53 | CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); 54 | 55 | if ([response.MIMEType isEqualToString:@"image/png"]) { 56 | imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); 57 | } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { 58 | imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); 59 | } 60 | 61 | if (!imageRef) { 62 | UIImage *image = AFImageWithDataAtScale(data, scale); 63 | if (image.images) { 64 | CGDataProviderRelease(dataProvider); 65 | 66 | return image; 67 | } 68 | 69 | imageRef = CGImageCreateCopy([image CGImage]); 70 | } 71 | 72 | CGDataProviderRelease(dataProvider); 73 | 74 | if (!imageRef) { 75 | return nil; 76 | } 77 | 78 | size_t width = CGImageGetWidth(imageRef); 79 | size_t height = CGImageGetHeight(imageRef); 80 | size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); 81 | size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate() 82 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 83 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 84 | 85 | if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 86 | int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); 87 | if (alpha == kCGImageAlphaNone) { 88 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 89 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 90 | } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { 91 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 92 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 93 | } 94 | } 95 | 96 | CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); 97 | 98 | CGColorSpaceRelease(colorSpace); 99 | 100 | if (!context) { 101 | CGImageRelease(imageRef); 102 | 103 | return [[UIImage alloc] initWithData:data]; 104 | } 105 | 106 | CGRect rect = CGRectMake(0.0f, 0.0f, width, height); 107 | CGContextDrawImage(context, rect, imageRef); 108 | CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); 109 | CGContextRelease(context); 110 | 111 | UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:UIImageOrientationUp]; 112 | CGImageRelease(inflatedImageRef); 113 | CGImageRelease(imageRef); 114 | 115 | return inflatedImage; 116 | } 117 | #endif 118 | 119 | @interface AFImageRequestOperation () 120 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 121 | @property (readwrite, nonatomic, strong) UIImage *responseImage; 122 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 123 | @property (readwrite, nonatomic, strong) NSImage *responseImage; 124 | #endif 125 | @end 126 | 127 | @implementation AFImageRequestOperation 128 | @synthesize responseImage = _responseImage; 129 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 130 | @synthesize imageScale = _imageScale; 131 | #endif 132 | 133 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 134 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 135 | success:(void (^)(UIImage *image))success 136 | { 137 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { 138 | if (success) { 139 | success(image); 140 | } 141 | } failure:nil]; 142 | } 143 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 144 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 145 | success:(void (^)(NSImage *image))success 146 | { 147 | return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) { 148 | if (success) { 149 | success(image); 150 | } 151 | } failure:nil]; 152 | } 153 | #endif 154 | 155 | 156 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 157 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 158 | imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock 159 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 160 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 161 | { 162 | AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; 163 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 164 | if (success) { 165 | UIImage *image = responseObject; 166 | if (imageProcessingBlock) { 167 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 168 | UIImage *processedImage = imageProcessingBlock(image); 169 | #pragma clang diagnostic push 170 | #pragma clang diagnostic ignored "-Wgnu" 171 | dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 172 | success(operation.request, operation.response, processedImage); 173 | }); 174 | #pragma clang diagnostic pop 175 | }); 176 | } else { 177 | success(operation.request, operation.response, image); 178 | } 179 | } 180 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 181 | if (failure) { 182 | failure(operation.request, operation.response, error); 183 | } 184 | }]; 185 | 186 | 187 | return requestOperation; 188 | } 189 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 190 | + (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest 191 | imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock 192 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success 193 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 194 | { 195 | AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; 196 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 197 | if (success) { 198 | NSImage *image = responseObject; 199 | if (imageProcessingBlock) { 200 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 201 | NSImage *processedImage = imageProcessingBlock(image); 202 | 203 | dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { 204 | success(operation.request, operation.response, processedImage); 205 | }); 206 | }); 207 | } else { 208 | success(operation.request, operation.response, image); 209 | } 210 | } 211 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 212 | if (failure) { 213 | failure(operation.request, operation.response, error); 214 | } 215 | }]; 216 | 217 | return requestOperation; 218 | } 219 | #endif 220 | 221 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 222 | self = [super initWithRequest:urlRequest]; 223 | if (!self) { 224 | return nil; 225 | } 226 | 227 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 228 | self.imageScale = [[UIScreen mainScreen] scale]; 229 | self.automaticallyInflatesResponseImage = YES; 230 | #endif 231 | 232 | return self; 233 | } 234 | 235 | 236 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 237 | - (UIImage *)responseImage { 238 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 239 | if (self.automaticallyInflatesResponseImage) { 240 | self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale); 241 | } else { 242 | self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale); 243 | } 244 | } 245 | 246 | return _responseImage; 247 | } 248 | 249 | - (void)setImageScale:(CGFloat)imageScale { 250 | #pragma clang diagnostic push 251 | #pragma clang diagnostic ignored "-Wfloat-equal" 252 | if (imageScale == _imageScale) { 253 | return; 254 | } 255 | #pragma clang diagnostic pop 256 | 257 | _imageScale = imageScale; 258 | 259 | self.responseImage = nil; 260 | } 261 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 262 | - (NSImage *)responseImage { 263 | if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { 264 | // Ensure that the image is set to it's correct pixel width and height 265 | NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData]; 266 | self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; 267 | [self.responseImage addRepresentation:bitimage]; 268 | } 269 | 270 | return _responseImage; 271 | } 272 | #endif 273 | 274 | #pragma mark - AFHTTPRequestOperation 275 | 276 | + (NSSet *)acceptableContentTypes { 277 | 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]; 278 | } 279 | 280 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 281 | static NSSet * _acceptablePathExtension = nil; 282 | static dispatch_once_t onceToken; 283 | dispatch_once(&onceToken, ^{ 284 | _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; 285 | }); 286 | 287 | return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request]; 288 | } 289 | 290 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 291 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 292 | { 293 | #pragma clang diagnostic push 294 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 295 | #pragma clang diagnostic ignored "-Wgnu" 296 | 297 | self.completionBlock = ^ { 298 | dispatch_async(image_request_operation_processing_queue(), ^(void) { 299 | if (self.error) { 300 | if (failure) { 301 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 302 | failure(self, self.error); 303 | }); 304 | } 305 | } else { 306 | if (success) { 307 | #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 308 | UIImage *image = nil; 309 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 310 | NSImage *image = nil; 311 | #endif 312 | 313 | image = self.responseImage; 314 | 315 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 316 | success(self, image); 317 | }); 318 | } 319 | } 320 | }); 321 | }; 322 | #pragma clang diagnostic pop 323 | } 324 | 325 | @end 326 | -------------------------------------------------------------------------------- /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 use the built-in `NSJSONSerialization` class. 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 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". 51 | */ 52 | @property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions; 53 | 54 | ///---------------------------------- 55 | /// @name Creating Request Operations 56 | ///---------------------------------- 57 | 58 | /** 59 | Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. 60 | 61 | @param urlRequest The request object to be loaded asynchronously during execution of the operation 62 | @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. 63 | @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. 64 | 65 | @return A new JSON request operation 66 | */ 67 | + (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure; 70 | 71 | @end 72 | -------------------------------------------------------------------------------- /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 json_request_operation_processing_queue() { 26 | static dispatch_queue_t af_json_request_operation_processing_queue; 27 | static dispatch_once_t onceToken; 28 | dispatch_once(&onceToken, ^{ 29 | af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT); 30 | }); 31 | 32 | return af_json_request_operation_processing_queue; 33 | } 34 | 35 | @interface AFJSONRequestOperation () 36 | @property (readwrite, nonatomic, strong) id responseJSON; 37 | @property (readwrite, nonatomic, strong) NSError *JSONError; 38 | @property (readwrite, nonatomic, strong) NSRecursiveLock *lock; 39 | @end 40 | 41 | @implementation AFJSONRequestOperation 42 | @synthesize responseJSON = _responseJSON; 43 | @synthesize JSONReadingOptions = _JSONReadingOptions; 44 | @synthesize JSONError = _JSONError; 45 | @dynamic lock; 46 | 47 | + (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest 48 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 49 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure 50 | { 51 | AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest]; 52 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 53 | if (success) { 54 | success(operation.request, operation.response, responseObject); 55 | } 56 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 57 | if (failure) { 58 | failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]); 59 | } 60 | }]; 61 | 62 | return requestOperation; 63 | } 64 | 65 | 66 | - (id)responseJSON { 67 | [self.lock lock]; 68 | if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) { 69 | NSError *error = nil; 70 | 71 | // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. 72 | // See https://github.com/rails/rails/issues/1742 73 | if (self.responseString && ![self.responseString isEqualToString:@" "]) { 74 | // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character 75 | // See http://stackoverflow.com/a/12843465/157142 76 | NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding]; 77 | 78 | if (data) { 79 | self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error]; 80 | } else { 81 | NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; 82 | [userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey]; 83 | [userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey]; 84 | error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; 85 | } 86 | } 87 | 88 | self.JSONError = error; 89 | } 90 | [self.lock unlock]; 91 | 92 | return _responseJSON; 93 | } 94 | 95 | - (NSError *)error { 96 | if (_JSONError) { 97 | return _JSONError; 98 | } else { 99 | return [super error]; 100 | } 101 | } 102 | 103 | #pragma mark - AFHTTPRequestOperation 104 | 105 | + (NSSet *)acceptableContentTypes { 106 | return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; 107 | } 108 | 109 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 110 | return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request]; 111 | } 112 | 113 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 114 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 115 | { 116 | #pragma clang diagnostic push 117 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 118 | #pragma clang diagnostic ignored "-Wgnu" 119 | 120 | self.completionBlock = ^ { 121 | if (self.error) { 122 | if (failure) { 123 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 124 | failure(self, self.error); 125 | }); 126 | } 127 | } else { 128 | dispatch_async(json_request_operation_processing_queue(), ^{ 129 | id JSON = self.responseJSON; 130 | 131 | if (self.error) { 132 | if (failure) { 133 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 134 | failure(self, self.error); 135 | }); 136 | } 137 | } else { 138 | if (success) { 139 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 140 | success(self, JSON); 141 | }); 142 | } 143 | } 144 | }); 145 | } 146 | }; 147 | #pragma clang diagnostic pop 148 | } 149 | 150 | @end 151 | -------------------------------------------------------------------------------- /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 defined(__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 | 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 | + (instancetype)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 | -------------------------------------------------------------------------------- /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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 28 | static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; 29 | 30 | @interface AFNetworkActivityIndicatorManager () 31 | @property (readwrite, nonatomic, assign) NSInteger activityCount; 32 | @property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; 33 | @property (readonly, nonatomic, 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 | + (instancetype)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(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; 66 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) 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 | 109 | dispatch_async(dispatch_get_main_queue(), ^{ 110 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 111 | }); 112 | } 113 | 114 | - (void)incrementActivityCount { 115 | [self willChangeValueForKey:@"activityCount"]; 116 | @synchronized(self) { 117 | _activityCount++; 118 | } 119 | [self didChangeValueForKey:@"activityCount"]; 120 | 121 | dispatch_async(dispatch_get_main_queue(), ^{ 122 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 123 | }); 124 | } 125 | 126 | - (void)decrementActivityCount { 127 | [self willChangeValueForKey:@"activityCount"]; 128 | @synchronized(self) { 129 | #pragma clang diagnostic push 130 | #pragma clang diagnostic ignored "-Wgnu" 131 | _activityCount = MAX(_activityCount - 1, 0); 132 | #pragma clang diagnostic pop 133 | } 134 | [self didChangeValueForKey:@"activityCount"]; 135 | 136 | dispatch_async(dispatch_get_main_queue(), ^{ 137 | [self updateNetworkActivityIndicatorVisibilityDelayed]; 138 | }); 139 | } 140 | 141 | - (void)networkingOperationDidStart:(NSNotification *)notification { 142 | AFURLConnectionOperation *connectionOperation = [notification object]; 143 | if (connectionOperation.request.URL) { 144 | [self incrementActivityCount]; 145 | } 146 | } 147 | 148 | - (void)networkingOperationDidFinish:(NSNotification *)notification { 149 | AFURLConnectionOperation *connectionOperation = [notification object]; 150 | if (connectionOperation.request.URL) { 151 | [self decrementActivityCount]; 152 | } 153 | } 154 | 155 | @end 156 | 157 | #endif 158 | -------------------------------------------------------------------------------- /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 defined(__IPHONE_OS_VERSION_MIN_REQUIRED) 40 | #import "AFNetworkActivityIndicatorManager.h" 41 | #import "UIImageView+AFNetworking.h" 42 | #endif 43 | #endif /* _AFNETWORKING_ */ 44 | -------------------------------------------------------------------------------- /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 | + (instancetype)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 | -------------------------------------------------------------------------------- /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 property_list_request_operation_processing_queue() { 26 | static dispatch_queue_t af_property_list_request_operation_processing_queue; 27 | static dispatch_once_t onceToken; 28 | dispatch_once(&onceToken, ^{ 29 | af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT); 30 | }); 31 | 32 | return af_property_list_request_operation_processing_queue; 33 | } 34 | 35 | @interface AFPropertyListRequestOperation () 36 | @property (readwrite, nonatomic) id responsePropertyList; 37 | @property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; 38 | @property (readwrite, nonatomic) NSError *propertyListError; 39 | @end 40 | 41 | @implementation AFPropertyListRequestOperation 42 | @synthesize responsePropertyList = _responsePropertyList; 43 | @synthesize propertyListReadOptions = _propertyListReadOptions; 44 | @synthesize propertyListFormat = _propertyListFormat; 45 | @synthesize propertyListError = _propertyListError; 46 | 47 | + (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request 48 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success 49 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure 50 | { 51 | AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request]; 52 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 53 | if (success) { 54 | success(operation.request, operation.response, responseObject); 55 | } 56 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 57 | if (failure) { 58 | failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]); 59 | } 60 | }]; 61 | 62 | return requestOperation; 63 | } 64 | 65 | - (id)initWithRequest:(NSURLRequest *)urlRequest { 66 | self = [super initWithRequest:urlRequest]; 67 | if (!self) { 68 | return nil; 69 | } 70 | 71 | self.propertyListReadOptions = NSPropertyListImmutable; 72 | 73 | return self; 74 | } 75 | 76 | 77 | - (id)responsePropertyList { 78 | if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) { 79 | NSPropertyListFormat format; 80 | NSError *error = nil; 81 | self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; 82 | self.propertyListFormat = format; 83 | self.propertyListError = error; 84 | } 85 | 86 | return _responsePropertyList; 87 | } 88 | 89 | - (NSError *)error { 90 | if (_propertyListError) { 91 | return _propertyListError; 92 | } else { 93 | return [super error]; 94 | } 95 | } 96 | 97 | #pragma mark - AFHTTPRequestOperation 98 | 99 | + (NSSet *)acceptableContentTypes { 100 | return [NSSet setWithObjects:@"application/x-plist", nil]; 101 | } 102 | 103 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 104 | return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request]; 105 | } 106 | 107 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 108 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 109 | { 110 | #pragma clang diagnostic push 111 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 112 | #pragma clang diagnostic ignored "-Wgnu" 113 | self.completionBlock = ^ { 114 | if (self.error) { 115 | if (failure) { 116 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 117 | failure(self, self.error); 118 | }); 119 | } 120 | } else { 121 | dispatch_async(property_list_request_operation_processing_queue(), ^(void) { 122 | id propertyList = self.responsePropertyList; 123 | 124 | if (self.propertyListError) { 125 | if (failure) { 126 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 127 | failure(self, self.error); 128 | }); 129 | } 130 | } else { 131 | if (success) { 132 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 133 | success(self, propertyList); 134 | }); 135 | } 136 | } 137 | }); 138 | } 139 | }; 140 | #pragma clang diagnostic pop 141 | } 142 | 143 | @end 144 | -------------------------------------------------------------------------------- /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 | + (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 70 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 71 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))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 | + (instancetype)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/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 xml_request_operation_processing_queue() { 28 | static dispatch_queue_t af_xml_request_operation_processing_queue; 29 | static dispatch_once_t onceToken; 30 | dispatch_once(&onceToken, ^{ 31 | af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT); 32 | }); 33 | 34 | return af_xml_request_operation_processing_queue; 35 | } 36 | 37 | @interface AFXMLRequestOperation () 38 | @property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser; 39 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 40 | @property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument; 41 | #endif 42 | @property (readwrite, nonatomic, strong) NSError *XMLError; 43 | @end 44 | 45 | @implementation AFXMLRequestOperation 46 | @synthesize responseXMLParser = _responseXMLParser; 47 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 48 | @synthesize responseXMLDocument = _responseXMLDocument; 49 | #endif 50 | @synthesize XMLError = _XMLError; 51 | 52 | + (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest 53 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success 54 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure 55 | { 56 | AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest]; 57 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 58 | if (success) { 59 | success(operation.request, operation.response, responseObject); 60 | } 61 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 62 | if (failure) { 63 | failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]); 64 | } 65 | }]; 66 | 67 | return requestOperation; 68 | } 69 | 70 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 71 | + (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest 72 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success 73 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure 74 | { 75 | AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; 76 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) { 77 | if (success) { 78 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 79 | success(operation.request, operation.response, XMLDocument); 80 | } 81 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 82 | if (failure) { 83 | NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; 84 | failure(operation.request, operation.response, error, XMLDocument); 85 | } 86 | }]; 87 | 88 | return requestOperation; 89 | } 90 | #endif 91 | 92 | 93 | - (NSXMLParser *)responseXMLParser { 94 | if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) { 95 | self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData]; 96 | } 97 | 98 | return _responseXMLParser; 99 | } 100 | 101 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 102 | - (NSXMLDocument *)responseXMLDocument { 103 | if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) { 104 | NSError *error = nil; 105 | self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error]; 106 | self.XMLError = error; 107 | } 108 | 109 | return _responseXMLDocument; 110 | } 111 | #endif 112 | 113 | - (NSError *)error { 114 | if (_XMLError) { 115 | return _XMLError; 116 | } else { 117 | return [super error]; 118 | } 119 | } 120 | 121 | #pragma mark - NSOperation 122 | 123 | - (void)cancel { 124 | [super cancel]; 125 | 126 | self.responseXMLParser.delegate = nil; 127 | } 128 | 129 | #pragma mark - AFHTTPRequestOperation 130 | 131 | + (NSSet *)acceptableContentTypes { 132 | return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; 133 | } 134 | 135 | + (BOOL)canProcessRequest:(NSURLRequest *)request { 136 | return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request]; 137 | } 138 | 139 | - (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 140 | failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure 141 | { 142 | #pragma clang diagnostic push 143 | #pragma clang diagnostic ignored "-Warc-retain-cycles" 144 | #pragma clang diagnostic ignored "-Wgnu" 145 | self.completionBlock = ^ { 146 | dispatch_async(xml_request_operation_processing_queue(), ^(void) { 147 | NSXMLParser *XMLParser = self.responseXMLParser; 148 | 149 | if (self.error) { 150 | if (failure) { 151 | dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ 152 | failure(self, self.error); 153 | }); 154 | } 155 | } else { 156 | if (success) { 157 | dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ 158 | success(self, XMLParser); 159 | }); 160 | } 161 | } 162 | }); 163 | }; 164 | #pragma clang diagnostic pop 165 | } 166 | 167 | @end 168 | -------------------------------------------------------------------------------- /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 | 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 | 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:` 49 | 50 | @param url The URL used for the image request. 51 | @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. 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 | If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed. 60 | 61 | @param urlRequest The URL request used for the image request. 62 | @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. 63 | @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`. 64 | @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. 65 | */ 66 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 67 | placeholderImage:(UIImage *)placeholderImage 68 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 69 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; 70 | 71 | /** 72 | Cancels any executing image request operation for the receiver, if one exists. 73 | */ 74 | - (void)cancelImageRequestOperation; 75 | 76 | @end 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /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 defined(__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 | static dispatch_once_t onceToken; 62 | dispatch_once(&onceToken, ^{ 63 | _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init]; 64 | [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; 65 | }); 66 | 67 | return _af_imageRequestOperationQueue; 68 | } 69 | 70 | + (AFImageCache *)af_sharedImageCache { 71 | static AFImageCache *_af_imageCache = nil; 72 | static dispatch_once_t oncePredicate; 73 | dispatch_once(&oncePredicate, ^{ 74 | _af_imageCache = [[AFImageCache alloc] init]; 75 | }); 76 | 77 | return _af_imageCache; 78 | } 79 | 80 | #pragma mark - 81 | 82 | - (void)setImageWithURL:(NSURL *)url { 83 | [self setImageWithURL:url placeholderImage:nil]; 84 | } 85 | 86 | - (void)setImageWithURL:(NSURL *)url 87 | placeholderImage:(UIImage *)placeholderImage 88 | { 89 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 90 | [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; 91 | 92 | [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; 93 | } 94 | 95 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 96 | placeholderImage:(UIImage *)placeholderImage 97 | success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success 98 | failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure 99 | { 100 | [self cancelImageRequestOperation]; 101 | 102 | UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest]; 103 | if (cachedImage) { 104 | if (success) { 105 | success(nil, nil, cachedImage); 106 | } else { 107 | self.image = cachedImage; 108 | } 109 | 110 | self.af_imageRequestOperation = nil; 111 | } else { 112 | if (placeholderImage) { 113 | self.image = placeholderImage; 114 | } 115 | 116 | AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; 117 | [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 118 | if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { 119 | if (success) { 120 | success(operation.request, operation.response, responseObject); 121 | } else if (responseObject) { 122 | self.image = responseObject; 123 | } 124 | 125 | if (self.af_imageRequestOperation == operation) { 126 | self.af_imageRequestOperation = nil; 127 | } 128 | } 129 | 130 | [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; 131 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 132 | if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { 133 | if (failure) { 134 | failure(operation.request, operation.response, error); 135 | } 136 | 137 | if (self.af_imageRequestOperation == operation) { 138 | self.af_imageRequestOperation = nil; 139 | } 140 | } 141 | }]; 142 | 143 | self.af_imageRequestOperation = requestOperation; 144 | 145 | [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; 146 | } 147 | } 148 | 149 | - (void)cancelImageRequestOperation { 150 | [self.af_imageRequestOperation cancel]; 151 | self.af_imageRequestOperation = nil; 152 | } 153 | 154 | @end 155 | 156 | #pragma mark - 157 | 158 | static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { 159 | return [[request URL] absoluteString]; 160 | } 161 | 162 | @implementation AFImageCache 163 | 164 | - (UIImage *)cachedImageForRequest:(NSURLRequest *)request { 165 | switch ([request cachePolicy]) { 166 | case NSURLRequestReloadIgnoringCacheData: 167 | case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: 168 | return nil; 169 | default: 170 | break; 171 | } 172 | 173 | return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; 174 | } 175 | 176 | - (void)cacheImage:(UIImage *)image 177 | forRequest:(NSURLRequest *)request 178 | { 179 | if (image && request) { 180 | [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; 181 | } 182 | } 183 | 184 | @end 185 | 186 | #endif 187 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | #import 27 | 28 | @interface AppDelegate : NSObject 29 | 30 | @property (nonatomic, strong) UIWindow *window; 31 | @property (nonatomic, strong) UINavigationController *navigationController; 32 | 33 | @end 34 | #else 35 | #import 36 | 37 | @interface AppDelegate : NSObject 38 | 39 | @property (strong) IBOutlet NSWindow *window; 40 | @property (strong) IBOutlet NSTableView *tableView; 41 | @property (strong) IBOutlet NSArrayController *postsArrayController; 42 | 43 | @end 44 | #endif 45 | -------------------------------------------------------------------------------- /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 | #import "GlobalTimelineViewController.h" 27 | 28 | #import "AFNetworkActivityIndicatorManager.h" 29 | 30 | @implementation AppDelegate 31 | @synthesize window = _window; 32 | @synthesize navigationController = _navigationController; 33 | 34 | - (BOOL)application:(UIApplication *)application 35 | didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 36 | { 37 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 38 | [NSURLCache setSharedURLCache:URLCache]; 39 | 40 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 41 | 42 | UITableViewController *viewController = [[GlobalTimelineViewController alloc] initWithStyle:UITableViewStylePlain]; 43 | self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; 44 | self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor]; 45 | 46 | self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 47 | self.window.backgroundColor = [UIColor whiteColor]; 48 | self.window.rootViewController = self.navigationController; 49 | [self.window makeKeyAndVisible]; 50 | 51 | return YES; 52 | } 53 | 54 | @end 55 | #else 56 | #import "Post.h" 57 | #import "User.h" 58 | 59 | @implementation AppDelegate 60 | 61 | @synthesize window = _window; 62 | @synthesize tableView = _tableView; 63 | @synthesize postsArrayController = _postsArrayController; 64 | 65 | - (void)applicationDidFinishLaunching:(NSNotification *)notification { 66 | NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil]; 67 | [NSURLCache setSharedURLCache:URLCache]; 68 | 69 | [self.window makeKeyAndOrderFront:self]; 70 | 71 | [Post globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) { 72 | if (error) { 73 | [[NSAlert alertWithMessageText:NSLocalizedString(@"Error", nil) defaultButton:NSLocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:@"%@",[error localizedDescription]] runModal]; 74 | } 75 | 76 | self.postsArrayController.content = posts; 77 | }]; 78 | 79 | [[NSNotificationCenter defaultCenter] addObserverForName:kUserProfileImageDidLoadNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { 80 | [self.tableView reloadData]; 81 | }]; 82 | } 83 | 84 | - (BOOL)applicationShouldHandleReopen:(NSApplication *)application 85 | hasVisibleWindows:(BOOL)flag 86 | { 87 | [self.window makeKeyAndOrderFront:self]; 88 | 89 | return YES; 90 | } 91 | 92 | @end 93 | #endif 94 | -------------------------------------------------------------------------------- /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/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 | // By default, the example ships with SSL pinning enabled for the app.net API pinned against the public key of adn.cer file included with the example. In order to make it easier for developers who are new to AFNetworking, SSL pinning is automatically disabled if the base URL has been changed. This will allow developers to hack around with the example, without getting tripped up by SSL pinning. 53 | if ([[url scheme] isEqualToString:@"https"] && [[url host] isEqualToString:@"alpha-api.app.net"]) { 54 | self.defaultSSLPinningMode = AFSSLPinningModePublicKey; 55 | } else { 56 | self.defaultSSLPinningMode = AFSSLPinningModeNone; 57 | } 58 | 59 | return self; 60 | } 61 | 62 | @end 63 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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 | NSArray *postsFromResponse = [JSON valueForKeyPath:@"data"]; 52 | NSMutableArray *mutablePosts = [NSMutableArray arrayWithCapacity:[postsFromResponse count]]; 53 | for (NSDictionary *attributes in postsFromResponse) { 54 | Post *post = [[Post alloc] initWithAttributes:attributes]; 55 | [mutablePosts addObject:post]; 56 | } 57 | 58 | if (block) { 59 | block([NSArray arrayWithArray:mutablePosts], nil); 60 | } 61 | } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 62 | if (block) { 63 | block([NSArray array], error); 64 | } 65 | }]; 66 | } 67 | 68 | @end 69 | -------------------------------------------------------------------------------- /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, nonatomic) NSUInteger userID; 30 | @property (readonly, nonatomic) NSString *username; 31 | @property (readonly, nonatomic, unsafe_unretained) 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Example/Default-568h@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Default-568h@2x.png -------------------------------------------------------------------------------- /Example/Default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Default.png -------------------------------------------------------------------------------- /Example/Default@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Default@2x.png -------------------------------------------------------------------------------- /Example/Icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Icon.png -------------------------------------------------------------------------------- /Example/Icon@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Icon@2x.png -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Images/profile-image-placeholder.png -------------------------------------------------------------------------------- /Example/Images/profile-image-placeholder@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/Images/profile-image-placeholder@2x.png -------------------------------------------------------------------------------- /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/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 -------------------------------------------------------------------------------- /Example/adn.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Example/adn.cer -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | AFNetworking 3 |

4 | 5 | [![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking) 6 | 7 | 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: 8 | 9 | ```objective-c 10 | NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]; 11 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 12 | AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 13 | NSLog(@"App.net Global Stream: %@", JSON); 14 | } failure:nil]; 15 | [operation start]; 16 | ``` 17 | 18 | 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. 19 | 20 | Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! 21 | 22 | ## How To Get Started 23 | 24 | - [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps 25 | - 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) 26 | - Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking 27 | - Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application 28 | - Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers 29 | 30 | ## Overview 31 | 32 | AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend. 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 | 60 | 61 | 62 | 63 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 |
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 64 | Captures the common patterns of communicating with an web application over HTTP, including: 65 | 66 |
    67 |
  • Making requests from relative paths of a base URL
  • 68 |
  • Setting HTTP headers to be added automatically to requests
  • 69 |
  • Authenticating requests with HTTP Basic credentials or an OAuth token
  • 70 |
  • Managing an NSOperationQueue for requests made by the client
  • 71 |
  • Generating query strings or HTTP bodies from an NSDictionary
  • 72 |
  • Constructing multipart form requests
  • 73 |
  • Automatically parsing HTTP response data into its corresponding object representation
  • 74 |
  • Monitoring and responding to changes in network reachability
  • 75 |
76 |
Images
AFImageRequestOperationA subclass of AFHTTPRequestOperation for downloading and processing images.
UIImageView+AFNetworkingAdds methods to UIImageView for loading remote images asynchronously from a URL.
89 | 90 | ## Example Usage 91 | 92 | ### XML Request 93 | 94 | ```objective-c 95 | 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"]]; 96 | AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) { 97 | XMLParser.delegate = self; 98 | [XMLParser parse]; 99 | } failure:nil]; 100 | [operation start]; 101 | ``` 102 | 103 | ### Image Request 104 | 105 | ```objective-c 106 | UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; 107 | [imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; 108 | ``` 109 | 110 | ### API Client Request 111 | 112 | ```objective-c 113 | // AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates 114 | [[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) { 115 | NSLog(@"App.net Global Stream: %@", JSON); 116 | } failure:nil]; 117 | ``` 118 | 119 | ### File Upload with Progress Callback 120 | 121 | ```objective-c 122 | NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; 123 | AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 124 | NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); 125 | NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) { 126 | [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; 127 | }]; 128 | 129 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 130 | [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 131 | NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); 132 | }]; 133 | [httpClient enqueueHTTPRequestOperation:operation]; 134 | ``` 135 | 136 | ### Streaming Request 137 | 138 | ```objective-c 139 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]]; 140 | 141 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 142 | operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]]; 143 | operation.outputStream = [NSOutputStream outputStreamToMemory]; 144 | [operation start]; 145 | ``` 146 | 147 | ## Requirements 148 | 149 | 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. 150 | 151 | For compatibility with iOS 4.3, use the latest 0.10.x release. 152 | 153 | ### ARC 154 | 155 | AFNetworking uses ARC as of its 1.0 release. 156 | 157 | 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. 158 | 159 | 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. 160 | 161 | ## Unit Tests 162 | 163 | AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so: 164 | 165 | $ gem install cocoapods # If necessary 166 | $ cd Tests 167 | $ pod install 168 | 169 | Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode. 170 | 171 | ### Test Logging 172 | 173 | By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the [AFHTTPRequestOperationLogger](https://github.com/AFNetworking/AFHTTPRequestOperationLogger) extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named `AFTestsLoggingEnabled` with a value of `YES`. 174 | 175 | ### Using xctool 176 | 177 | If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install [xctool](https://github.com/facebook/xctool). The recommended installation method is [Homebrew](http://mxcl.github.io/homebrew/). 178 | 179 | To install the commandline testing support via Homebrew: 180 | 181 | $ brew update 182 | $ brew install xctool --HEAD 183 | 184 | Once xctool is installed, you can execute the suite via `rake test`. 185 | 186 | ## Credits 187 | 188 | 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). 189 | 190 | AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). 191 | 192 | And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). 193 | 194 | ## Contact 195 | 196 | Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking)) 197 | 198 | ### Creators 199 | 200 | [Mattt Thompson](http://github.com/mattt) 201 | [@mattt](https://twitter.com/mattt) 202 | 203 | [Scott Raymond](http://github.com/sco) 204 | [@sco](https://twitter.com/sco) 205 | 206 | ## License 207 | 208 | AFNetworking is available under the MIT license. See the LICENSE file for more info. 209 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | namespace :test do 2 | task :prepare do 3 | system(%Q{mkdir -p "Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes" && cp Tests/Schemes/*.xcscheme "Tests/AFNetworking Tests.xcodeproj/xcshareddata/xcschemes/"}) 4 | end 5 | 6 | desc "Run the AFNetworking Tests for iOS" 7 | task :ios => :prepare do 8 | $ios_success = system("xctool -workspace AFNetworking.xcworkspace -scheme 'iOS Tests' -sdk iphonesimulator -configuration Release test -test-sdk iphonesimulator") 9 | end 10 | 11 | desc "Run the AFNetworking Tests for Mac OS X" 12 | task :osx => :prepare do 13 | $osx_success = system("xctool -workspace AFNetworking.xcworkspace -scheme 'OS X Tests' -sdk macosx -configuration Release test -test-sdk macosx") 14 | end 15 | end 16 | 17 | desc "Run the AFNetworking Tests for iOS & Mac OS X" 18 | task :test => ['test:ios', 'test:osx'] do 19 | puts "\033[0;31m! iOS unit tests failed" unless $ios_success 20 | puts "\033[0;31m! OS X unit tests failed" unless $osx_success 21 | if $ios_success && $osx_success 22 | puts "\033[0;32m** All tests executed successfully" 23 | else 24 | exit(-1) 25 | end 26 | end 27 | 28 | task :default => 'test' 29 | -------------------------------------------------------------------------------- /Tests/AFHTTPRequestOperationTests.m: -------------------------------------------------------------------------------- 1 | // AFHTTPRequestOperationTests.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworkingTests.h" 24 | 25 | @interface AFHTTPRequestOperationTests : SenTestCase 26 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 27 | @end 28 | 29 | @implementation AFHTTPRequestOperationTests 30 | @synthesize baseURL = _baseURL; 31 | 32 | - (void)setUp { 33 | self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 34 | } 35 | 36 | #pragma mark - 37 | 38 | - (void)testThatOperationInvokesSuccessCompletionBlockWithResponseObjectOnSuccess { 39 | __block id blockResponseObject = nil; 40 | 41 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/get" relativeToURL:self.baseURL]]; 42 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 43 | [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 44 | blockResponseObject = responseObject; 45 | } failure:nil]; 46 | 47 | [operation start]; 48 | expect([operation isFinished]).will.beTruthy(); 49 | expect(blockResponseObject).willNot.beNil(); 50 | } 51 | 52 | - (void)testThatOperationInvokesFailureCompletionBlockWithErrorOnFailure { 53 | __block NSError *blockError = nil; 54 | 55 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 56 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 57 | [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) { 58 | blockError = error; 59 | }]; 60 | 61 | [operation start]; 62 | expect([operation isFinished]).will.beTruthy(); 63 | expect(blockError).willNot.beNil(); 64 | } 65 | 66 | - (void)testThatCancellationOfRequestOperationSetsError { 67 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/5" relativeToURL:self.baseURL]]; 68 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 69 | 70 | [operation start]; 71 | expect([operation isExecuting]).will.beTruthy(); 72 | 73 | [operation cancel]; 74 | expect(operation.error).willNot.beNil(); 75 | expect(operation.error.code).to.equal(NSURLErrorCancelled); 76 | } 77 | 78 | - (void)testThatCancellationOfRequestOperationInvokesFailureCompletionBlock { 79 | __block NSError *blockError = nil; 80 | 81 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/5" relativeToURL:self.baseURL]]; 82 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 83 | [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) { 84 | blockError = error; 85 | }]; 86 | 87 | [operation start]; 88 | expect([operation isExecuting]).will.beTruthy(); 89 | 90 | [operation cancel]; 91 | expect(operation.error).willNot.beNil(); 92 | expect(blockError).willNot.beNil(); 93 | expect(blockError.code).will.equal(NSURLErrorCancelled); 94 | } 95 | 96 | - (void)testThat500StatusCodeInvokesFailureCompletionBlockWithErrorOnFailure { 97 | __block NSError *blockError = nil; 98 | 99 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/500" relativeToURL:self.baseURL]]; 100 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 101 | [operation setCompletionBlockWithSuccess:nil failure:^(AFHTTPRequestOperation *operation, NSError *error) { 102 | blockError = error; 103 | }]; 104 | 105 | [operation start]; 106 | expect([operation isFinished]).will.beTruthy(); 107 | expect(blockError).willNot.beNil(); 108 | } 109 | 110 | - (void)testThatRedirectBlockIsCalledWhen302IsEncountered { 111 | __block BOOL success; 112 | 113 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/1" relativeToURL:self.baseURL]]; 114 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 115 | [operation setCompletionBlockWithSuccess:nil failure:nil]; 116 | [operation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { 117 | if(redirectResponse){ 118 | success = YES; 119 | } 120 | 121 | return request; 122 | }]; 123 | 124 | [operation start]; 125 | expect([operation isFinished]).will.beTruthy(); 126 | expect(success).will.beTruthy(); 127 | } 128 | 129 | - (void)testThatRedirectBlockIsCalledMultipleTimesWhenMultiple302sAreEncountered { 130 | [Expecta setAsynchronousTestTimeout:5.0]; 131 | __block NSInteger numberOfRedirects = 0; 132 | 133 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/redirect/5" relativeToURL:self.baseURL]]; 134 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 135 | [operation setCompletionBlockWithSuccess:nil failure:nil]; 136 | [operation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) { 137 | if(redirectResponse){ 138 | numberOfRedirects++; 139 | } 140 | 141 | return request; 142 | }]; 143 | 144 | [operation start]; 145 | expect([operation isFinished]).will.beTruthy(); 146 | expect(numberOfRedirects).will.equal(5); 147 | } 148 | 149 | #pragma mark - Pause 150 | 151 | - (void)testThatOperationCanBePaused { 152 | [Expecta setAsynchronousTestTimeout:3.0]; 153 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]]; 154 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 155 | 156 | [operation start]; 157 | expect([operation isExecuting]).will.beTruthy(); 158 | 159 | [operation pause]; 160 | expect([operation isPaused]).will.beTruthy(); 161 | [operation cancel]; 162 | } 163 | 164 | - (void)testThatPausedOperationCanBeResumed { 165 | [Expecta setAsynchronousTestTimeout:3.0]; 166 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]]; 167 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 168 | 169 | [operation start]; 170 | expect([operation isExecuting]).will.beTruthy(); 171 | 172 | [operation pause]; 173 | expect([operation isPaused]).will.beTruthy(); 174 | 175 | [operation resume]; 176 | expect([operation isExecuting]).will.beTruthy(); 177 | 178 | [operation cancel]; 179 | } 180 | 181 | - (void)testThatPausedOperationCanBeCompleted { 182 | [Expecta setAsynchronousTestTimeout:3.0]; 183 | 184 | __block id blockResponseObject = nil; 185 | 186 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/delay/1" relativeToURL:self.baseURL]]; 187 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 188 | [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 189 | blockResponseObject = responseObject; 190 | } failure:nil]; 191 | 192 | [operation start]; 193 | expect([operation isExecuting]).will.beTruthy(); 194 | 195 | [operation pause]; 196 | expect([operation isPaused]).will.beTruthy(); 197 | 198 | [operation resume]; 199 | expect([operation isExecuting]).will.beTruthy(); 200 | expect([operation isFinished]).will.beTruthy(); 201 | expect(blockResponseObject).willNot.beNil(); 202 | } 203 | 204 | #pragma mark - Response String Encoding 205 | 206 | - (void)testThatTextStringEncodingIsISOLatin1WhenNoCharsetParameterIsProvided { 207 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/plain" relativeToURL:self.baseURL]]; 208 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 209 | 210 | [operation start]; 211 | expect([operation isFinished]).will.beTruthy(); 212 | expect(operation.responseStringEncoding).will.equal(NSISOLatin1StringEncoding); 213 | } 214 | 215 | - (void)testThatTextStringEncodingIsShiftJISWhenShiftJISCharsetParameterIsProvided { 216 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/plain;%20charset=%22Shift_JIS%22" relativeToURL:self.baseURL]]; 217 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 218 | 219 | [operation start]; 220 | expect([operation isFinished]).will.beTruthy(); 221 | expect(operation.responseStringEncoding).will.equal(NSShiftJISStringEncoding); 222 | } 223 | 224 | - (void)testThatTextStringEncodingIsUTF8WhenInvalidCharsetParameterIsProvided { 225 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/plain;%20charset=%22invalid%22" relativeToURL:self.baseURL]]; 226 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 227 | 228 | [operation start]; 229 | expect([operation isFinished]).will.beTruthy(); 230 | expect(operation.responseStringEncoding).will.equal(NSUTF8StringEncoding); 231 | } 232 | 233 | - (void)testThatTextStringEncodingIsUTF8WhenUTF8CharsetParameterIsProvided { 234 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/plain;%20charset=%22UTF-8%22" relativeToURL:self.baseURL]]; 235 | AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 236 | 237 | [operation start]; 238 | expect([operation isFinished]).will.beTruthy(); 239 | expect(operation.responseStringEncoding).will.equal(NSUTF8StringEncoding); 240 | } 241 | 242 | @end 243 | -------------------------------------------------------------------------------- /Tests/AFImageRequestOperationTests.m: -------------------------------------------------------------------------------- 1 | // AFImageRequestOperationTests.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworkingTests.h" 24 | 25 | @interface AFImageRequestOperationTests : SenTestCase 26 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 27 | @end 28 | 29 | @implementation AFImageRequestOperationTests 30 | @synthesize baseURL = _baseURL; 31 | 32 | - (void)setUp { 33 | self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 34 | } 35 | 36 | #pragma mark - 37 | 38 | - (void)testThatImageRequestOperationAcceptsTIFFContentType { 39 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/tiff" relativeToURL:self.baseURL]]; 40 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 41 | [operation start]; 42 | 43 | expect([operation isFinished]).will.beTruthy(); 44 | expect(operation.error).will.beNil(); 45 | } 46 | 47 | - (void)testThatImageRequestOperationAcceptsJPEGContentType { 48 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/jpeg" relativeToURL:self.baseURL]]; 49 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 50 | [operation start]; 51 | 52 | expect([operation isFinished]).will.beTruthy(); 53 | expect(operation.error).will.beNil(); 54 | } 55 | 56 | - (void)testThatImageRequestOperationAcceptsGIFContentType { 57 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/gif" relativeToURL:self.baseURL]]; 58 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 59 | [operation start]; 60 | 61 | expect([operation isFinished]).will.beTruthy(); 62 | expect(operation.error).will.beNil(); 63 | } 64 | 65 | - (void)testThatImageRequestOperationAcceptsPNGContentType { 66 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/png" relativeToURL:self.baseURL]]; 67 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 68 | [operation start]; 69 | 70 | expect([operation isFinished]).will.beTruthy(); 71 | expect(operation.error).will.beNil(); 72 | } 73 | 74 | - (void)testThatImageRequestOperationAcceptsIconContentTypes { 75 | NSArray *acceptableIconContentTypes = @[@"image/ico", @"image/x-icon"]; 76 | for (NSString *contentType in acceptableIconContentTypes) { 77 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"/response-headers?Content-Type=%@", contentType] relativeToURL:self.baseURL]]; 78 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 79 | [operation start]; 80 | 81 | expect([operation isFinished]).will.beTruthy(); 82 | expect(operation.error).will.beNil(); 83 | } 84 | } 85 | 86 | - (void)testThatImageRequestOperationAcceptsBitmapContentTypes { 87 | NSArray *acceptableBitmapContentTypes = @[@"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap"]; 88 | for (NSString *contentType in acceptableBitmapContentTypes) { 89 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"/response-headers?Content-Type=%@", contentType] relativeToURL:self.baseURL]]; 90 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 91 | [operation start]; 92 | 93 | expect([operation isFinished]).will.beTruthy(); 94 | expect(operation.error).will.beNil(); 95 | } 96 | } 97 | 98 | - (void)testThatImageRequestOperationDoesNotAcceptInvalidFormatTypes { 99 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/invalid" relativeToURL:self.baseURL]]; 100 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 101 | [operation start]; 102 | 103 | expect([operation isFinished]).will.beTruthy(); 104 | expect(operation.error).willNot.beNil(); 105 | } 106 | 107 | - (void)testThatImageResponseIsNotNilWhenRequestSucceeds { 108 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"/image" relativeToURL:self.baseURL]]; 109 | [request setValue:@"image/png" forHTTPHeaderField:@"Accept"]; 110 | 111 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 112 | [operation start]; 113 | 114 | expect([operation isFinished]).will.beTruthy(); 115 | expect(operation.responseImage).willNot.beNil(); 116 | } 117 | 118 | - (void)testThatImageResponseIsNilWhenRequestFails { 119 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 120 | AFImageRequestOperation *operation = [[AFImageRequestOperation alloc] initWithRequest:request]; 121 | [operation start]; 122 | 123 | expect([operation isFinished]).will.beTruthy(); 124 | expect(operation.responseImage).will.beNil(); 125 | } 126 | 127 | - (void)testImageProcessingBlockIsRunOnSuccess { 128 | __block BOOL imageProcessingBlockExecuted = NO; 129 | 130 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=image/png" relativeToURL:self.baseURL]]; 131 | AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:^UIImage *(UIImage *image) { 132 | imageProcessingBlockExecuted = YES; 133 | return image; 134 | } success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 135 | return; 136 | } failure:nil]; 137 | 138 | [operation start]; 139 | expect([operation isFinished]).will.beTruthy(); 140 | expect(operation.error).will.beNil(); 141 | expect(imageProcessingBlockExecuted).will.beTruthy(); 142 | } 143 | 144 | - (void)testImageProcessingBlockIsNotRunOnFailure { 145 | __block UIImage *blockImage = nil; 146 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 147 | 148 | AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:^UIImage *(UIImage *image) { 149 | blockImage = [[UIImage alloc] init]; 150 | return blockImage; 151 | } success:nil failure:nil]; 152 | [operation start]; 153 | 154 | expect([operation isFinished]).will.beTruthy(); 155 | expect(operation.error).willNot.beNil(); 156 | expect(blockImage).will.beNil(); 157 | } 158 | 159 | @end 160 | -------------------------------------------------------------------------------- /Tests/AFJSONRequestOperationTests.m: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperationTests.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworkingTests.h" 24 | 25 | @interface AFJSONRequestOperationTests : SenTestCase 26 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 27 | @end 28 | 29 | @implementation AFJSONRequestOperationTests 30 | @synthesize baseURL = _baseURL; 31 | 32 | - (void)setUp { 33 | self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 34 | } 35 | 36 | - (void)testThatJSONRequestOperationAcceptsApplicationJSON { 37 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/json" relativeToURL:self.baseURL]]; 38 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 39 | 40 | [operation start]; 41 | expect([operation isFinished]).will.beTruthy(); 42 | expect(operation.error).will.beNil(); 43 | } 44 | 45 | - (void)testThatJSONRequestOperationAcceptsTextJSON { 46 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/json" relativeToURL:self.baseURL]]; 47 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 48 | 49 | [operation start]; 50 | expect([operation isFinished]).will.beTruthy(); 51 | expect(operation.error).will.beNil(); 52 | } 53 | 54 | - (void)testThatJSONRequestOperationAcceptsTextJavascript { 55 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=text/javascript" relativeToURL:self.baseURL]]; 56 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 57 | 58 | [operation start]; 59 | expect([operation isFinished]).will.beTruthy(); 60 | expect(operation.error).will.beNil(); 61 | } 62 | 63 | - (void)testThatJSONRequestOperationAcceptsCustomContentType { 64 | [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/customjson"]]; 65 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/customjson" relativeToURL:self.baseURL]]; 66 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 67 | 68 | [operation start]; 69 | expect([operation isFinished]).will.beTruthy(); 70 | expect(operation.error).will.beNil(); 71 | } 72 | 73 | - (void)testThatJSONRequestOperationDoesNotAcceptInvalidContentType { 74 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/no-json" relativeToURL:self.baseURL]]; 75 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 76 | 77 | [operation start]; 78 | expect([operation isFinished]).will.beTruthy(); 79 | expect(operation.error).willNot.beNil(); 80 | } 81 | 82 | - (void)testThatJSONResponseObjectIsNotNilWhenValidJSONIsReturned { 83 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/response-headers?Content-Type=application/json" relativeToURL:self.baseURL]]; 84 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 85 | 86 | [operation start]; 87 | expect([operation isFinished]).will.beTruthy(); 88 | expect(operation.responseJSON).willNot.beNil(); 89 | } 90 | 91 | - (void)testThatJSONResponseObjectIsNilWhenErrorOccurs { 92 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/status/404" relativeToURL:self.baseURL]]; 93 | AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request]; 94 | 95 | [operation start]; 96 | expect([operation isFinished]).will.beTruthy(); 97 | expect(operation.responseJSON).will.beNil(); 98 | } 99 | 100 | @end 101 | -------------------------------------------------------------------------------- /Tests/AFMockURLProtocol.h: -------------------------------------------------------------------------------- 1 | // AFMockURLProtocol.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "OCMock.h" 26 | 27 | @protocol AFMockURLProtocolProxy 28 | - (id)stub; 29 | - (id)expect; 30 | - (id)reject; 31 | @end 32 | 33 | @interface AFMockURLProtocol : NSURLProtocol 34 | 35 | + (void)handleNextRequestForURL:(NSURL *)URL 36 | usingBlock:(void (^)(AFMockURLProtocol * protocol))block; 37 | 38 | @end 39 | -------------------------------------------------------------------------------- /Tests/AFMockURLProtocol.m: -------------------------------------------------------------------------------- 1 | // AFMockURLProtocol.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFMockURLProtocol.h" 24 | 25 | typedef void (^AFTestURLProtocolInitializationCallback)(AFMockURLProtocol *protocol); 26 | 27 | static volatile NSURL * _matchingURL = nil; 28 | static volatile AFTestURLProtocolInitializationCallback _initializationCallback = nil; 29 | 30 | @implementation AFMockURLProtocol 31 | 32 | + (void)load { 33 | [NSURLProtocol registerClass:[AFMockURLProtocol class]]; 34 | } 35 | 36 | + (void)handleNextRequestForURL:(NSURL *)URL 37 | usingBlock:(void (^)(AFMockURLProtocol * protocol))block; 38 | { 39 | _matchingURL = URL; 40 | _initializationCallback = block; 41 | } 42 | 43 | #pragma mark - NSURLProtocol 44 | 45 | + (BOOL)canInitWithRequest:(NSURLRequest *)request { 46 | return [request.URL isEqual:_matchingURL] && _initializationCallback; 47 | } 48 | 49 | + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { 50 | return request; 51 | } 52 | 53 | + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a 54 | toRequest:(NSURLRequest *)b 55 | { 56 | return NO; 57 | } 58 | 59 | - (id)initWithRequest:(NSURLRequest *)request 60 | cachedResponse:(NSCachedURLResponse *)cachedResponse 61 | client:(id )client 62 | { 63 | self = [super initWithRequest:request cachedResponse:cachedResponse client:client]; 64 | if (!self) { 65 | return nil; 66 | } 67 | 68 | if (_initializationCallback) { 69 | self = [OCMockObject partialMockForObject:self]; 70 | 71 | _initializationCallback(self); 72 | } 73 | 74 | _initializationCallback = nil; 75 | _matchingURL = nil; 76 | 77 | return self; 78 | } 79 | 80 | - (void)startLoading {} 81 | 82 | - (void)stopLoading {} 83 | 84 | #pragma mark - NSURLAuthenticationChallengeSender 85 | 86 | - (void)cancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 87 | [self doesNotRecognizeSelector:_cmd]; 88 | } 89 | 90 | - (void)continueWithoutCredentialForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 91 | [self doesNotRecognizeSelector:_cmd]; 92 | } 93 | 94 | - (void)useCredential:(NSURLCredential *)credential 95 | forAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 96 | [self doesNotRecognizeSelector:_cmd]; 97 | } 98 | 99 | - (void)performDefaultHandlingForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 100 | [self doesNotRecognizeSelector:_cmd]; 101 | } 102 | 103 | - (void)rejectProtectionSpaceAndContinueWithChallenge:(NSURLAuthenticationChallenge *)challenge { 104 | [self doesNotRecognizeSelector:_cmd]; 105 | } 106 | 107 | @end 108 | -------------------------------------------------------------------------------- /Tests/AFNetworking-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header for all source files of the 'AFNetworking' target in the 'AFNetworking' project 3 | // 4 | 5 | #ifdef __OBJC__ 6 | #import 7 | 8 | #import 9 | #if __IPHONE_OS_VERSION_MIN_REQUIRED 10 | #import 11 | #import 12 | #else 13 | #import 14 | #import 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /Tests/AFNetworkingTests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | org.afnetworking.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Tests/AFNetworkingTests.h: -------------------------------------------------------------------------------- 1 | // AFNetworkingTests.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworking.h" 25 | 26 | #define EXP_SHORTHAND YES 27 | #import "Expecta.h" 28 | #import "OCMock.h" 29 | 30 | extern NSString * const AFNetworkingTestsBaseURLString; 31 | 32 | @interface AFNetworkingTests : NSObject 33 | @end 34 | -------------------------------------------------------------------------------- /Tests/AFNetworkingTests.m: -------------------------------------------------------------------------------- 1 | // AFNetworkingTests.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworkingTests.h" 24 | #import "AFHTTPRequestOperationLogger.h" 25 | 26 | NSString * const AFNetworkingTestsBaseURLString = @"http://httpbin.org/"; 27 | 28 | @implementation AFNetworkingTests 29 | 30 | + (void)load { 31 | if ([[[[[NSProcessInfo processInfo] environment] valueForKey:@"AFTestsLoggingEnabled"] uppercaseString] isEqualToString:@"YES"]) { 32 | [[AFHTTPRequestOperationLogger sharedLogger] startLogging]; 33 | } 34 | } 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /Tests/AFURLConnectionOperationTests.m: -------------------------------------------------------------------------------- 1 | // AFJSONRequestOperationTests.m 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.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 "AFNetworkingTests.h" 24 | #import "AFURLConnectionOperation.h" 25 | #import "AFMockURLProtocol.h" 26 | 27 | @interface AFURLConnectionOperationTests : SenTestCase 28 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 29 | @end 30 | 31 | @implementation AFURLConnectionOperationTests 32 | @synthesize baseURL = _baseURL; 33 | 34 | - (void)setUp { 35 | self.baseURL = [NSURL URLWithString:AFNetworkingTestsBaseURLString]; 36 | } 37 | 38 | #pragma mark - 39 | 40 | - (void)testThatAFURLConnectionOperationInvokesWillSendRequestForAuthenticationChallengeBlock { 41 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]]; 42 | AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; 43 | 44 | __block BOOL willSendRequestForAuthenticationChallengeBlockInvoked = NO; 45 | [operation setWillSendRequestForAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) { 46 | willSendRequestForAuthenticationChallengeBlockInvoked = YES; 47 | }]; 48 | 49 | [AFMockURLProtocol handleNextRequestForURL:request.URL usingBlock:^(AFMockURLProtocol * protocol) { 50 | 51 | void(^startOperation)(NSInvocation *invocation) = ^(NSInvocation *invocation) { 52 | __unsafe_unretained AFMockURLProtocol *protocol = nil; 53 | [invocation getArgument:&protocol atIndex:0]; 54 | 55 | NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodDefault]; 56 | NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:nil previousFailureCount:0 failureResponse:nil error:nil sender:protocol]; 57 | [protocol.client URLProtocol:protocol didReceiveAuthenticationChallenge:authenticationChallenge]; 58 | }; 59 | [[[protocol stub] andDo:startOperation] startLoading]; 60 | }]; 61 | 62 | [operation start]; 63 | expect(willSendRequestForAuthenticationChallengeBlockInvoked).will.beTruthy(); 64 | 65 | [operation cancel]; 66 | } 67 | 68 | - (void)testThatAFURLConnectionOperationTrustsPinnedCertificates { 69 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]]; 70 | AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; 71 | operation.SSLPinningMode = AFSSLPinningModeCertificate; 72 | 73 | __block BOOL useCredentialInvoked = NO; 74 | 75 | NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust]; 76 | 77 | NSData *certificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"root_certificate" ofType:@"cer"]]; 78 | NSParameterAssert(certificateData); 79 | 80 | SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData); 81 | NSParameterAssert(certificate); 82 | 83 | SecCertificateRef allowedCertificates[] = {certificate}; 84 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); 85 | 86 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 87 | SecTrustRef trust = NULL; 88 | OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); 89 | NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); 90 | 91 | SecTrustResultType result; 92 | status = SecTrustEvaluate(trust, &result); 93 | NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); 94 | 95 | id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace]; 96 | 97 | [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) { 98 | [invocation setReturnValue:(void *)&trust]; 99 | }] serverTrust]; 100 | 101 | AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil]; 102 | id mockedProtocol = [OCMockObject partialMockForObject:protocol]; 103 | 104 | void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) { 105 | useCredentialInvoked = YES; 106 | }; 107 | 108 | [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY]; 109 | 110 | NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust]; 111 | NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol]; 112 | [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge]; 113 | 114 | [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge]; 115 | 116 | CFRelease(trust); 117 | CFRelease(policy); 118 | CFRelease(certificates); 119 | CFRelease(certificate); 120 | 121 | expect(useCredentialInvoked).will.beTruthy(); 122 | } 123 | 124 | - (void)testThatAFURLConnectionOperationTrustsPinnedPublicKeys { 125 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]]; 126 | AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; 127 | operation.SSLPinningMode = AFSSLPinningModePublicKey; 128 | 129 | __block BOOL useCredentialInvoked = NO; 130 | 131 | NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust]; 132 | 133 | NSData *certificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"root_certificate" ofType:@"cer"]]; 134 | NSParameterAssert(certificateData); 135 | 136 | SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData); 137 | NSParameterAssert(certificate); 138 | 139 | SecCertificateRef allowedCertificates[] = {certificate}; 140 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); 141 | 142 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 143 | SecTrustRef trust = NULL; 144 | OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); 145 | NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); 146 | 147 | SecTrustResultType result; 148 | status = SecTrustEvaluate(trust, &result); 149 | NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); 150 | 151 | id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace]; 152 | 153 | [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) { 154 | [invocation setReturnValue:(void *)&trust]; 155 | }] serverTrust]; 156 | 157 | AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil]; 158 | id mockedProtocol = [OCMockObject partialMockForObject:protocol]; 159 | 160 | void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) { 161 | useCredentialInvoked = YES; 162 | }; 163 | 164 | [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY]; 165 | 166 | NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust]; 167 | NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol]; 168 | [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge]; 169 | 170 | [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge]; 171 | 172 | CFRelease(trust); 173 | CFRelease(policy); 174 | CFRelease(certificates); 175 | CFRelease(certificate); 176 | 177 | expect(useCredentialInvoked).will.beTruthy(); 178 | } 179 | 180 | - (void)testThatAFURLConnectionOperationTrustsPublicKeysOfDerivedCertificates { 181 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]]; 182 | AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; 183 | operation.SSLPinningMode = AFSSLPinningModePublicKey; 184 | 185 | __block BOOL useCredentialInvoked = NO; 186 | 187 | NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust]; 188 | 189 | NSData *caCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ca" ofType:@"cer"]]; 190 | NSParameterAssert(caCertificateData); 191 | 192 | SecCertificateRef caCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData); 193 | NSParameterAssert(caCertificate); 194 | 195 | NSData *hostCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"derived" ofType:@"cert"]]; 196 | NSParameterAssert(hostCertificateData); 197 | 198 | SecCertificateRef hostCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData); 199 | NSParameterAssert(hostCertificate); 200 | 201 | SecCertificateRef allowedCertificates[] = {caCertificate, hostCertificate}; 202 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 2, NULL); 203 | 204 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 205 | SecTrustRef trust = NULL; 206 | OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); 207 | NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); 208 | 209 | SecTrustResultType result; 210 | status = SecTrustEvaluate(trust, &result); 211 | NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); 212 | 213 | id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace]; 214 | 215 | [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) { 216 | [invocation setReturnValue:(void *)&trust]; 217 | }] serverTrust]; 218 | 219 | AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil]; 220 | id mockedProtocol = [OCMockObject partialMockForObject:protocol]; 221 | 222 | void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) { 223 | useCredentialInvoked = YES; 224 | }; 225 | 226 | [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY]; 227 | 228 | NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust]; 229 | NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol]; 230 | [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge]; 231 | 232 | [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge]; 233 | 234 | CFRelease(trust); 235 | CFRelease(policy); 236 | CFRelease(certificates); 237 | CFRelease(caCertificate); 238 | CFRelease(hostCertificate); 239 | 240 | expect(useCredentialInvoked).will.beTruthy(); 241 | } 242 | 243 | - (void)testThatAFURLConnectionOperationTrustsDerivedCertificates { 244 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"/path" relativeToURL:self.baseURL]]; 245 | AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; 246 | operation.SSLPinningMode = AFSSLPinningModeCertificate; 247 | 248 | __block BOOL useCredentialInvoked = NO; 249 | 250 | NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:request.URL.host port:request.URL.port.integerValue protocol:request.URL.scheme realm:nil authenticationMethod:NSURLAuthenticationMethodServerTrust]; 251 | 252 | NSData *caCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"ca" ofType:@"cer"]]; 253 | NSParameterAssert(caCertificateData); 254 | 255 | SecCertificateRef caCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData); 256 | NSParameterAssert(caCertificate); 257 | 258 | NSData *hostCertificateData = [NSData dataWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"derived" ofType:@"cert"]]; 259 | NSParameterAssert(hostCertificateData); 260 | 261 | SecCertificateRef hostCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)caCertificateData); 262 | NSParameterAssert(hostCertificate); 263 | 264 | SecCertificateRef allowedCertificates[] = {caCertificate, hostCertificate}; 265 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 2, NULL); 266 | 267 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 268 | SecTrustRef trust = NULL; 269 | OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); 270 | NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); 271 | 272 | SecTrustResultType result; 273 | status = SecTrustEvaluate(trust, &result); 274 | NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); 275 | 276 | id mockedProtectionSpace = [OCMockObject partialMockForObject:protectionSpace]; 277 | 278 | [[[mockedProtectionSpace stub] andDo:^(NSInvocation *invocation) { 279 | [invocation setReturnValue:(void *)&trust]; 280 | }] serverTrust]; 281 | 282 | AFMockURLProtocol *protocol = [[AFMockURLProtocol alloc] initWithRequest:request cachedResponse:nil client:nil]; 283 | id mockedProtocol = [OCMockObject partialMockForObject:protocol]; 284 | 285 | void(^useCredential)(NSInvocation *invocation) = ^(NSInvocation *invocation) { 286 | useCredentialInvoked = YES; 287 | }; 288 | 289 | [[[mockedProtocol stub] andDo:useCredential] useCredential:OCMOCK_ANY forAuthenticationChallenge:OCMOCK_ANY]; 290 | 291 | NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust]; 292 | NSURLAuthenticationChallenge *authenticationChallenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:protectionSpace proposedCredential:credential previousFailureCount:0 failureResponse:nil error:nil sender:mockedProtocol]; 293 | [protocol.client URLProtocol:mockedProtocol didReceiveAuthenticationChallenge:authenticationChallenge]; 294 | 295 | [operation connection:nil willSendRequestForAuthenticationChallenge:authenticationChallenge]; 296 | 297 | CFRelease(trust); 298 | CFRelease(policy); 299 | CFRelease(certificates); 300 | CFRelease(caCertificate); 301 | CFRelease(hostCertificate); 302 | 303 | expect(useCredentialInvoked).will.beTruthy(); 304 | } 305 | 306 | @end 307 | -------------------------------------------------------------------------------- /Tests/Podfile: -------------------------------------------------------------------------------- 1 | xcodeproj 'AFNetworking Tests' 2 | workspace '../AFNetworking' 3 | inhibit_all_warnings! 4 | 5 | def import_pods 6 | pod 'OCMock', '~> 2.1.1' 7 | pod 'Expecta', '~> 0.2.1' 8 | pod 'AFHTTPRequestOperationLogger', '~> 0.10.0' 9 | pod 'AFNetworking', :path => '../' 10 | end 11 | 12 | target :ios do 13 | platform :ios, '5.0' 14 | link_with 'iOS Tests' 15 | import_pods 16 | end 17 | 18 | target :osx do 19 | platform :osx, '10.7' 20 | link_with 'OS X Tests' 21 | import_pods 22 | end 23 | -------------------------------------------------------------------------------- /Tests/Podfile.lock: -------------------------------------------------------------------------------- 1 | PODS: 2 | - AFHTTPRequestOperationLogger (0.10.0): 3 | - AFNetworking (>= 0.9.0) 4 | - AFNetworking (1.3.1) 5 | - Expecta (0.2.1) 6 | - OCMock (2.1.1) 7 | 8 | DEPENDENCIES: 9 | - AFHTTPRequestOperationLogger (~> 0.10.0) 10 | - AFNetworking (from `../`) 11 | - Expecta (~> 0.2.1) 12 | - OCMock (~> 2.1.1) 13 | 14 | EXTERNAL SOURCES: 15 | AFNetworking: 16 | :path: ../ 17 | 18 | SPEC CHECKSUMS: 19 | AFHTTPRequestOperationLogger: 34ba125cb9eeb77a3b67aaaca105720ba3a0798c 20 | AFNetworking: 9ec8aafb9269236a7630bd8d9838ce2ba30fa2a0 21 | Expecta: d46fb1bd78c90a83da0158b9b1e108de106e369f 22 | OCMock: 79212e5e328378af5cfd6edb5feacfd6c49cd8a3 23 | 24 | COCOAPODS: 0.22.2 25 | -------------------------------------------------------------------------------- /Tests/Resources/ca.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Tests/Resources/ca.cer -------------------------------------------------------------------------------- /Tests/Resources/derived.cert: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Tests/Resources/derived.cert -------------------------------------------------------------------------------- /Tests/Resources/root_certificate.cer: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/github/AFNetworking/46211ece01a2432432d135fcf8c52def8121e23c/Tests/Resources/root_certificate.cer -------------------------------------------------------------------------------- /Tests/Resources/root_certificate.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICXAIBAAKBgQCc9QJKFLopeILA83YzRmFenXIcgfIIaIbfCbFbvm/ntwCtZ7eK 3 | cqGBA2SI/kSEJGpIkpzq0lyb1ZJB8ayGD8p8lKfxnmOsc1RSzXz3cieomqF3ftIF 4 | 21yp79qnwo8roWV2AAolWnmcpCwbrWmgbWueupl7ieu4gcSOXU4EikwGKwIDAQAB 5 | AoGASq0zmqWD8Sk6JK1xJnIs74Q/f5q/2gpJaSLGdJ0FxxxFwTsgk0l419YSZi97 6 | z9c3jjHbYMoXb7lMbf2bFOm8b4zQvmdVpLbiHC9Lned30VHgZJ55WSPd0GQJl9EJ 7 | uw4C9J2Uk7uUjQbbgGPHwO5w/75F++Cp5jN91M/7fqgxO9kCQQDMC15vSVrHR0hU 8 | GO235KeaDIUlIWBQYcPXZTn2kBfpSE2T3aYuIqfM5fx0z5A4nSM9Ylo/FOrm+y/p 9 | ogT+APTFAkEAxOxAn09r9vx46drP8ap8ca2+0x46+1xVoaAdUv/OlXV4Ftgo5l7h 10 | 5ZRvs+JILmtvErtzkaUiCudh96F3tLAeLwJAOXO2ClW4NsYuamd+f7nlKy39S2Aj 11 | c16juwFombEm2mueVFUjlnfxkXLsa6OJ8zbjlkQcLwjfv1vYuMsC5tY0FQJBAJcd 12 | hWm7lOpwTImI9NJLNjw2TJ3OMQz7imsBZ/9tdqaTApjlQF2oqkl3Y1DzcNjOcOo7 13 | FzDJPBqJ/U/+hNIP5NkCQCUhCnfTXxx48sL7XKjlTr66rEbk3e1rZL7vx+24jcax 14 | xUooGhnRWaQsbEynVteYbPg7I8e8N6YEHtW5jwxhFaE= 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /Tests/Schemes/OS X Tests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 52 | 53 | 54 | 55 | 61 | 62 | 64 | 65 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /Tests/Schemes/iOS Tests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 52 | 53 | 54 | 55 | 61 | 62 | 64 | 65 | 68 | 69 | 70 | --------------------------------------------------------------------------------