Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

AFURLResponseSerialization.m 27KB

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