AFURLResponseSerialization.m 26 KB

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