AFURLResponseSerialization.m 27 KB

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