AFURLResponseSerialization.m 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // AFURLResponseSerialization.m
  2. // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
  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. #import "AFURLResponseSerialization.h"
  22. #if TARGET_OS_IOS
  23. #import <UIKit/UIKit.h>
  24. #elif TARGET_OS_WATCH
  25. #import <WatchKit/WatchKit.h>
  26. #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  27. #import <Cocoa/Cocoa.h>
  28. #endif
  29. NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response";
  30. NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response";
  31. NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data";
  32. static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) {
  33. if (!error) {
  34. return underlyingError;
  35. }
  36. if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) {
  37. return error;
  38. }
  39. NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy];
  40. mutableUserInfo[NSUnderlyingErrorKey] = underlyingError;
  41. return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo];
  42. }
  43. static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) {
  44. if ([error.domain isEqualToString:domain] && error.code == code) {
  45. return YES;
  46. } else if (error.userInfo[NSUnderlyingErrorKey]) {
  47. return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain);
  48. }
  49. return NO;
  50. }
  51. static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) {
  52. if ([JSONObject isKindOfClass:[NSArray class]]) {
  53. NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
  54. for (id value in (NSArray *)JSONObject) {
  55. [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)];
  56. }
  57. return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
  58. } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
  59. NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
  60. for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
  61. id value = (NSDictionary *)JSONObject[key];
  62. if (!value || [value isEqual:[NSNull null]]) {
  63. [mutableDictionary removeObjectForKey:key];
  64. } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
  65. mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions);
  66. }
  67. }
  68. return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
  69. }
  70. return JSONObject;
  71. }
  72. @implementation AFHTTPResponseSerializer
  73. + (instancetype)serializer {
  74. return [[self alloc] init];
  75. }
  76. - (instancetype)init {
  77. self = [super init];
  78. if (!self) {
  79. return nil;
  80. }
  81. self.stringEncoding = NSUTF8StringEncoding;
  82. self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)];
  83. self.acceptableContentTypes = nil;
  84. return self;
  85. }
  86. #pragma mark -
  87. - (BOOL)validateResponse:(NSHTTPURLResponse *)response
  88. data:(NSData *)data
  89. error:(NSError * __autoreleasing *)error
  90. {
  91. BOOL responseIsValid = YES;
  92. NSError *validationError = nil;
  93. if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
  94. if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) {
  95. if ([data length] > 0 && [response URL]) {
  96. NSMutableDictionary *mutableUserInfo = [@{
  97. NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
  98. NSURLErrorFailingURLErrorKey:[response URL],
  99. AFNetworkingOperationFailingURLResponseErrorKey: response,
  100. } mutableCopy];
  101. if (data) {
  102. mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
  103. }
  104. validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
  105. }
  106. responseIsValid = NO;
  107. }
  108. if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
  109. NSMutableDictionary *mutableUserInfo = [@{
  110. NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
  111. NSURLErrorFailingURLErrorKey:[response URL],
  112. AFNetworkingOperationFailingURLResponseErrorKey: response,
  113. } mutableCopy];
  114. if (data) {
  115. mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
  116. }
  117. validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
  118. responseIsValid = NO;
  119. }
  120. }
  121. if (error && !responseIsValid) {
  122. *error = validationError;
  123. }
  124. return responseIsValid;
  125. }
  126. #pragma mark - AFURLResponseSerialization
  127. - (id)responseObjectForResponse:(NSURLResponse *)response
  128. data:(NSData *)data
  129. error:(NSError *__autoreleasing *)error
  130. {
  131. [self validateResponse:(NSHTTPURLResponse *)response data:data error:error];
  132. return data;
  133. }
  134. #pragma mark - NSSecureCoding
  135. + (BOOL)supportsSecureCoding {
  136. return YES;
  137. }
  138. - (id)initWithCoder:(NSCoder *)decoder {
  139. self = [self init];
  140. if (!self) {
  141. return nil;
  142. }
  143. self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
  144. self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
  145. return self;
  146. }
  147. - (void)encodeWithCoder:(NSCoder *)coder {
  148. [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))];
  149. [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))];
  150. }
  151. #pragma mark - NSCopying
  152. - (id)copyWithZone:(NSZone *)zone {
  153. AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  154. serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone];
  155. serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone];
  156. return serializer;
  157. }
  158. @end
  159. #pragma mark -
  160. @implementation AFJSONResponseSerializer
  161. + (instancetype)serializer {
  162. return [self serializerWithReadingOptions:(NSJSONReadingOptions)0];
  163. }
  164. + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions {
  165. AFJSONResponseSerializer *serializer = [[self alloc] init];
  166. serializer.readingOptions = readingOptions;
  167. return serializer;
  168. }
  169. - (instancetype)init {
  170. self = [super init];
  171. if (!self) {
  172. return nil;
  173. }
  174. self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
  175. return self;
  176. }
  177. #pragma mark - AFURLResponseSerialization
  178. - (id)responseObjectForResponse:(NSURLResponse *)response
  179. data:(NSData *)data
  180. error:(NSError *__autoreleasing *)error
  181. {
  182. if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  183. if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  184. return nil;
  185. }
  186. }
  187. // 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.
  188. // See https://github.com/rails/rails/issues/1742
  189. NSStringEncoding stringEncoding = self.stringEncoding;
  190. if (response.textEncodingName) {
  191. CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
  192. if (encoding != kCFStringEncodingInvalidId) {
  193. stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
  194. }
  195. }
  196. id responseObject = nil;
  197. NSError *serializationError = nil;
  198. @autoreleasepool {
  199. NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
  200. if (responseString && ![responseString isEqualToString:@" "]) {
  201. // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
  202. // See http://stackoverflow.com/a/12843465/157142
  203. data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
  204. if (data) {
  205. if ([data length] > 0) {
  206. responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
  207. } else {
  208. return nil;
  209. }
  210. } else {
  211. NSDictionary *userInfo = @{
  212. NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil),
  213. NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString]
  214. };
  215. serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
  216. }
  217. }
  218. }
  219. if (self.removesKeysWithNullValues && responseObject) {
  220. responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
  221. }
  222. if (error) {
  223. *error = AFErrorWithUnderlyingError(serializationError, *error);
  224. }
  225. return responseObject;
  226. }
  227. #pragma mark - NSSecureCoding
  228. - (id)initWithCoder:(NSCoder *)decoder {
  229. self = [super initWithCoder:decoder];
  230. if (!self) {
  231. return nil;
  232. }
  233. self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue];
  234. self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue];
  235. return self;
  236. }
  237. - (void)encodeWithCoder:(NSCoder *)coder {
  238. [super encodeWithCoder:coder];
  239. [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))];
  240. [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))];
  241. }
  242. #pragma mark - NSCopying
  243. - (id)copyWithZone:(NSZone *)zone {
  244. AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  245. serializer.readingOptions = self.readingOptions;
  246. serializer.removesKeysWithNullValues = self.removesKeysWithNullValues;
  247. return serializer;
  248. }
  249. @end
  250. #pragma mark -
  251. @implementation AFXMLParserResponseSerializer
  252. + (instancetype)serializer {
  253. AFXMLParserResponseSerializer *serializer = [[self alloc] init];
  254. return serializer;
  255. }
  256. - (instancetype)init {
  257. self = [super init];
  258. if (!self) {
  259. return nil;
  260. }
  261. self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
  262. return self;
  263. }
  264. #pragma mark - AFURLResponseSerialization
  265. - (id)responseObjectForResponse:(NSHTTPURLResponse *)response
  266. data:(NSData *)data
  267. error:(NSError *__autoreleasing *)error
  268. {
  269. if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  270. if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  271. return nil;
  272. }
  273. }
  274. return [[NSXMLParser alloc] initWithData:data];
  275. }
  276. @end
  277. #pragma mark -
  278. #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED
  279. @implementation AFXMLDocumentResponseSerializer
  280. + (instancetype)serializer {
  281. return [self serializerWithXMLDocumentOptions:0];
  282. }
  283. + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask {
  284. AFXMLDocumentResponseSerializer *serializer = [[self alloc] init];
  285. serializer.options = mask;
  286. return serializer;
  287. }
  288. - (instancetype)init {
  289. self = [super init];
  290. if (!self) {
  291. return nil;
  292. }
  293. self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil];
  294. return self;
  295. }
  296. #pragma mark - AFURLResponseSerialization
  297. - (id)responseObjectForResponse:(NSURLResponse *)response
  298. data:(NSData *)data
  299. error:(NSError *__autoreleasing *)error
  300. {
  301. if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  302. if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  303. return nil;
  304. }
  305. }
  306. NSError *serializationError = nil;
  307. NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError];
  308. if (error) {
  309. *error = AFErrorWithUnderlyingError(serializationError, *error);
  310. }
  311. return document;
  312. }
  313. #pragma mark - NSSecureCoding
  314. - (id)initWithCoder:(NSCoder *)decoder {
  315. self = [super initWithCoder:decoder];
  316. if (!self) {
  317. return nil;
  318. }
  319. self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue];
  320. return self;
  321. }
  322. - (void)encodeWithCoder:(NSCoder *)coder {
  323. [super encodeWithCoder:coder];
  324. [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))];
  325. }
  326. #pragma mark - NSCopying
  327. - (id)copyWithZone:(NSZone *)zone {
  328. AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  329. serializer.options = self.options;
  330. return serializer;
  331. }
  332. @end
  333. #endif
  334. #pragma mark -
  335. @implementation AFPropertyListResponseSerializer
  336. + (instancetype)serializer {
  337. return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0];
  338. }
  339. + (instancetype)serializerWithFormat:(NSPropertyListFormat)format
  340. readOptions:(NSPropertyListReadOptions)readOptions
  341. {
  342. AFPropertyListResponseSerializer *serializer = [[self alloc] init];
  343. serializer.format = format;
  344. serializer.readOptions = readOptions;
  345. return serializer;
  346. }
  347. - (instancetype)init {
  348. self = [super init];
  349. if (!self) {
  350. return nil;
  351. }
  352. self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil];
  353. return self;
  354. }
  355. #pragma mark - AFURLResponseSerialization
  356. - (id)responseObjectForResponse:(NSURLResponse *)response
  357. data:(NSData *)data
  358. error:(NSError *__autoreleasing *)error
  359. {
  360. if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  361. if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  362. return nil;
  363. }
  364. }
  365. id responseObject;
  366. NSError *serializationError = nil;
  367. if (data) {
  368. responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
  369. }
  370. if (error) {
  371. *error = AFErrorWithUnderlyingError(serializationError, *error);
  372. }
  373. return responseObject;
  374. }
  375. #pragma mark - NSSecureCoding
  376. - (id)initWithCoder:(NSCoder *)decoder {
  377. self = [super initWithCoder:decoder];
  378. if (!self) {
  379. return nil;
  380. }
  381. self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue];
  382. self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue];
  383. return self;
  384. }
  385. - (void)encodeWithCoder:(NSCoder *)coder {
  386. [super encodeWithCoder:coder];
  387. [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))];
  388. [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))];
  389. }
  390. #pragma mark - NSCopying
  391. - (id)copyWithZone:(NSZone *)zone {
  392. AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  393. serializer.format = self.format;
  394. serializer.readOptions = self.readOptions;
  395. return serializer;
  396. }
  397. @end
  398. #pragma mark -
  399. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  400. #import <CoreGraphics/CoreGraphics.h>
  401. @interface UIImage (AFNetworkingSafeImageLoading)
  402. + (UIImage *)af_safeImageWithData:(NSData *)data;
  403. @end
  404. static NSLock* imageLock = nil;
  405. @implementation UIImage (AFNetworkingSafeImageLoading)
  406. + (UIImage *)af_safeImageWithData:(NSData *)data {
  407. UIImage* image = nil;
  408. static dispatch_once_t onceToken;
  409. dispatch_once(&onceToken, ^{
  410. imageLock = [[NSLock alloc] init];
  411. });
  412. [imageLock lock];
  413. image = [UIImage imageWithData:data];
  414. [imageLock unlock];
  415. return image;
  416. }
  417. @end
  418. static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) {
  419. UIImage *image = [UIImage af_safeImageWithData:data];
  420. if (image.images) {
  421. return image;
  422. }
  423. return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation];
  424. }
  425. static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) {
  426. if (!data || [data length] == 0) {
  427. return nil;
  428. }
  429. CGImageRef imageRef = NULL;
  430. CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
  431. if ([response.MIMEType isEqualToString:@"image/png"]) {
  432. imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
  433. } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) {
  434. imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault);
  435. if (imageRef) {
  436. CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef);
  437. CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace);
  438. // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale
  439. if (imageColorSpaceModel == kCGColorSpaceModelCMYK) {
  440. CGImageRelease(imageRef);
  441. imageRef = NULL;
  442. }
  443. }
  444. }
  445. CGDataProviderRelease(dataProvider);
  446. UIImage *image = AFImageWithDataAtScale(data, scale);
  447. if (!imageRef) {
  448. if (image.images || !image) {
  449. return image;
  450. }
  451. imageRef = CGImageCreateCopy([image CGImage]);
  452. if (!imageRef) {
  453. return nil;
  454. }
  455. }
  456. size_t width = CGImageGetWidth(imageRef);
  457. size_t height = CGImageGetHeight(imageRef);
  458. size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
  459. if (width * height > 1024 * 1024 || bitsPerComponent > 8) {
  460. CGImageRelease(imageRef);
  461. return image;
  462. }
  463. // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate
  464. size_t bytesPerRow = 0;
  465. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  466. CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
  467. CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
  468. if (colorSpaceModel == kCGColorSpaceModelRGB) {
  469. uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask);
  470. #pragma clang diagnostic push
  471. #pragma clang diagnostic ignored "-Wassign-enum"
  472. if (alpha == kCGImageAlphaNone) {
  473. bitmapInfo &= ~kCGBitmapAlphaInfoMask;
  474. bitmapInfo |= kCGImageAlphaNoneSkipFirst;
  475. } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) {
  476. bitmapInfo &= ~kCGBitmapAlphaInfoMask;
  477. bitmapInfo |= kCGImageAlphaPremultipliedFirst;
  478. }
  479. #pragma clang diagnostic pop
  480. }
  481. CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
  482. CGColorSpaceRelease(colorSpace);
  483. if (!context) {
  484. CGImageRelease(imageRef);
  485. return image;
  486. }
  487. CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef);
  488. CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context);
  489. CGContextRelease(context);
  490. UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation];
  491. CGImageRelease(inflatedImageRef);
  492. CGImageRelease(imageRef);
  493. return inflatedImage;
  494. }
  495. #endif
  496. @implementation AFImageResponseSerializer
  497. - (instancetype)init {
  498. self = [super init];
  499. if (!self) {
  500. return nil;
  501. }
  502. self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"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];
  503. #if TARGET_OS_IOS
  504. self.imageScale = [[UIScreen mainScreen] scale];
  505. self.automaticallyInflatesResponseImage = YES;
  506. #elif TARGET_OS_WATCH
  507. self.imageScale = [[WKInterfaceDevice currentDevice] screenScale];
  508. self.automaticallyInflatesResponseImage = YES;
  509. #endif
  510. return self;
  511. }
  512. #pragma mark - AFURLResponseSerializer
  513. - (id)responseObjectForResponse:(NSURLResponse *)response
  514. data:(NSData *)data
  515. error:(NSError *__autoreleasing *)error
  516. {
  517. if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) {
  518. if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) {
  519. return nil;
  520. }
  521. }
  522. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  523. if (self.automaticallyInflatesResponseImage) {
  524. return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
  525. } else {
  526. return AFImageWithDataAtScale(data, self.imageScale);
  527. }
  528. #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
  529. // Ensure that the image is set to it's correct pixel width and height
  530. NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data];
  531. NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])];
  532. [image addRepresentation:bitimage];
  533. return image;
  534. #endif
  535. return nil;
  536. }
  537. #pragma mark - NSSecureCoding
  538. - (id)initWithCoder:(NSCoder *)decoder {
  539. self = [super initWithCoder:decoder];
  540. if (!self) {
  541. return nil;
  542. }
  543. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  544. NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))];
  545. #if CGFLOAT_IS_DOUBLE
  546. self.imageScale = [imageScale doubleValue];
  547. #else
  548. self.imageScale = [imageScale floatValue];
  549. #endif
  550. self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
  551. #endif
  552. return self;
  553. }
  554. - (void)encodeWithCoder:(NSCoder *)coder {
  555. [super encodeWithCoder:coder];
  556. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  557. [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))];
  558. [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))];
  559. #endif
  560. }
  561. #pragma mark - NSCopying
  562. - (id)copyWithZone:(NSZone *)zone {
  563. AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  564. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  565. serializer.imageScale = self.imageScale;
  566. serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage;
  567. #endif
  568. return serializer;
  569. }
  570. @end
  571. #pragma mark -
  572. @interface AFCompoundResponseSerializer ()
  573. @property (readwrite, nonatomic, copy) NSArray *responseSerializers;
  574. @end
  575. @implementation AFCompoundResponseSerializer
  576. + (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers {
  577. AFCompoundResponseSerializer *serializer = [[self alloc] init];
  578. serializer.responseSerializers = responseSerializers;
  579. return serializer;
  580. }
  581. #pragma mark - AFURLResponseSerialization
  582. - (id)responseObjectForResponse:(NSURLResponse *)response
  583. data:(NSData *)data
  584. error:(NSError *__autoreleasing *)error
  585. {
  586. for (id <AFURLResponseSerialization> serializer in self.responseSerializers) {
  587. if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) {
  588. continue;
  589. }
  590. NSError *serializerError = nil;
  591. id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError];
  592. if (responseObject) {
  593. if (error) {
  594. *error = AFErrorWithUnderlyingError(serializerError, *error);
  595. }
  596. return responseObject;
  597. }
  598. }
  599. return [super responseObjectForResponse:response data:data error:error];
  600. }
  601. #pragma mark - NSSecureCoding
  602. - (id)initWithCoder:(NSCoder *)decoder {
  603. self = [super initWithCoder:decoder];
  604. if (!self) {
  605. return nil;
  606. }
  607. self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))];
  608. return self;
  609. }
  610. - (void)encodeWithCoder:(NSCoder *)coder {
  611. [super encodeWithCoder:coder];
  612. [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))];
  613. }
  614. #pragma mark - NSCopying
  615. - (id)copyWithZone:(NSZone *)zone {
  616. AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init];
  617. serializer.responseSerializers = self.responseSerializers;
  618. return serializer;
  619. }
  620. @end