EMSDWebImageDownloaderOperation.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "EMSDWebImageDownloaderOperation.h"
  9. #import "EMSDWebImageDecoder.h"
  10. #import "UIImage+EMMultiFormat.h"
  11. #import <ImageIO/ImageIO.h>
  12. #import "EMSDWebImageManager.h"
  13. @interface EMSDWebImageDownloaderOperation () <NSURLConnectionDataDelegate>
  14. @property (copy, nonatomic) EMSDWebImageDownloaderProgressBlock progressBlock;
  15. @property (copy, nonatomic) EMSDWebImageDownloaderCompletedBlock completedBlock;
  16. @property (copy, nonatomic) EMSDWebImageNoParamsBlock cancelBlock;
  17. @property (assign, nonatomic, getter = isExecuting) BOOL executing;
  18. @property (assign, nonatomic, getter = isFinished) BOOL finished;
  19. @property (assign, nonatomic) NSInteger expectedSize;
  20. @property (strong, nonatomic) NSMutableData *imageData;
  21. @property (strong, nonatomic) NSURLConnection *connection;
  22. @property (strong, atomic) NSThread *thread;
  23. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  24. @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
  25. #endif
  26. @end
  27. @implementation EMSDWebImageDownloaderOperation {
  28. size_t width, height;
  29. UIImageOrientation orientation;
  30. BOOL responseFromCached;
  31. }
  32. @synthesize executing = _executing;
  33. @synthesize finished = _finished;
  34. - (id)initWithRequest:(NSURLRequest *)request
  35. options:(EMSDWebImageDownloaderOptions)options
  36. progress:(EMSDWebImageDownloaderProgressBlock)progressBlock
  37. completed:(EMSDWebImageDownloaderCompletedBlock)completedBlock
  38. cancelled:(EMSDWebImageNoParamsBlock)cancelBlock {
  39. if ((self = [super init])) {
  40. _request = request;
  41. _shouldUseCredentialStorage = YES;
  42. _options = options;
  43. _progressBlock = [progressBlock copy];
  44. _completedBlock = [completedBlock copy];
  45. _cancelBlock = [cancelBlock copy];
  46. _executing = NO;
  47. _finished = NO;
  48. _expectedSize = 0;
  49. responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called
  50. }
  51. return self;
  52. }
  53. - (void)start {
  54. @synchronized (self) {
  55. if (self.isCancelled) {
  56. self.finished = YES;
  57. [self reset];
  58. return;
  59. }
  60. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  61. if ([self shouldContinueWhenAppEntersBackground]) {
  62. __weak __typeof__ (self) wself = self;
  63. self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  64. __strong __typeof (wself) sself = wself;
  65. if (sself) {
  66. [sself cancel];
  67. [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
  68. sself.backgroundTaskId = UIBackgroundTaskInvalid;
  69. }
  70. }];
  71. }
  72. #endif
  73. self.executing = YES;
  74. self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
  75. self.thread = [NSThread currentThread];
  76. }
  77. [self.connection start];
  78. if (self.connection) {
  79. if (self.progressBlock) {
  80. self.progressBlock(0, NSURLResponseUnknownLength);
  81. }
  82. [[NSNotificationCenter defaultCenter] postNotificationName:EMSDWebImageDownloadStartNotification object:self];
  83. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) {
  84. // Make sure to run the runloop in our background thread so it can process downloaded data
  85. // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5
  86. // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466)
  87. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
  88. }
  89. else {
  90. CFRunLoopRun();
  91. }
  92. if (!self.isFinished) {
  93. [self.connection cancel];
  94. [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]];
  95. }
  96. }
  97. else {
  98. if (self.completedBlock) {
  99. self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES);
  100. }
  101. }
  102. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  103. if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
  104. [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
  105. self.backgroundTaskId = UIBackgroundTaskInvalid;
  106. }
  107. #endif
  108. }
  109. - (void)cancel {
  110. @synchronized (self) {
  111. if (self.thread) {
  112. [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
  113. }
  114. else {
  115. [self cancelInternal];
  116. }
  117. }
  118. }
  119. - (void)cancelInternalAndStop {
  120. if (self.isFinished) return;
  121. [self cancelInternal];
  122. CFRunLoopStop(CFRunLoopGetCurrent());
  123. }
  124. - (void)cancelInternal {
  125. if (self.isFinished) return;
  126. [super cancel];
  127. if (self.cancelBlock) self.cancelBlock();
  128. if (self.connection) {
  129. [self.connection cancel];
  130. [[NSNotificationCenter defaultCenter] postNotificationName:EMSDWebImageDownloadStopNotification object:self];
  131. // As we cancelled the connection, its callback won't be called and thus won't
  132. // maintain the isFinished and isExecuting flags.
  133. if (self.isExecuting) self.executing = NO;
  134. if (!self.isFinished) self.finished = YES;
  135. }
  136. [self reset];
  137. }
  138. - (void)done {
  139. self.finished = YES;
  140. self.executing = NO;
  141. [self reset];
  142. }
  143. - (void)reset {
  144. self.cancelBlock = nil;
  145. self.completedBlock = nil;
  146. self.progressBlock = nil;
  147. self.connection = nil;
  148. self.imageData = nil;
  149. self.thread = nil;
  150. }
  151. - (void)setFinished:(BOOL)finished {
  152. [self willChangeValueForKey:@"isFinished"];
  153. _finished = finished;
  154. [self didChangeValueForKey:@"isFinished"];
  155. }
  156. - (void)setExecuting:(BOOL)executing {
  157. [self willChangeValueForKey:@"isExecuting"];
  158. _executing = executing;
  159. [self didChangeValueForKey:@"isExecuting"];
  160. }
  161. - (BOOL)isConcurrent {
  162. return YES;
  163. }
  164. #pragma mark NSURLConnection (delegate)
  165. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  166. if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) {
  167. NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
  168. self.expectedSize = expected;
  169. if (self.progressBlock) {
  170. self.progressBlock(0, expected);
  171. }
  172. self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
  173. }
  174. else {
  175. [self.connection cancel];
  176. [[NSNotificationCenter defaultCenter] postNotificationName:EMSDWebImageDownloadStopNotification object:nil];
  177. if (self.completedBlock) {
  178. self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
  179. }
  180. CFRunLoopStop(CFRunLoopGetCurrent());
  181. [self done];
  182. }
  183. }
  184. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  185. [self.imageData appendData:data];
  186. if ((self.options & EMSDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) {
  187. // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
  188. // Thanks to the author @Nyx0uf
  189. // Get the total bytes downloaded
  190. const NSInteger totalSize = self.imageData.length;
  191. // Update the data source, we must pass ALL the data, not just the new bytes
  192. CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL);
  193. CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize);
  194. if (width + height == 0) {
  195. CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
  196. if (properties) {
  197. NSInteger orientationValue = -1;
  198. CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
  199. if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
  200. val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
  201. if (val) CFNumberGetValue(val, kCFNumberLongType, &width);
  202. val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
  203. if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
  204. CFRelease(properties);
  205. // When we draw to Core Graphics, we lose orientation information,
  206. // which means the image below born of initWithCGIImage will be
  207. // oriented incorrectly sometimes. (Unlike the image born of initWithData
  208. // in connectionDidFinishLoading.) So save it here and pass it on later.
  209. orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)];
  210. }
  211. }
  212. if (width + height > 0 && totalSize < self.expectedSize) {
  213. // Create the image
  214. CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
  215. #ifdef TARGET_OS_IPHONE
  216. // Workaround for iOS anamorphic image
  217. if (partialImageRef) {
  218. const size_t partialHeight = CGImageGetHeight(partialImageRef);
  219. CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
  220. CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
  221. CGColorSpaceRelease(colorSpace);
  222. if (bmContext) {
  223. CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
  224. CGImageRelease(partialImageRef);
  225. partialImageRef = CGBitmapContextCreateImage(bmContext);
  226. CGContextRelease(bmContext);
  227. }
  228. else {
  229. CGImageRelease(partialImageRef);
  230. partialImageRef = nil;
  231. }
  232. }
  233. #endif
  234. if (partialImageRef) {
  235. UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation];
  236. NSString *key = [[EMSDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
  237. UIImage *scaledImage = [self scaledImageForKey:key image:image];
  238. image = [UIImage decodedImageWithImage:scaledImage];
  239. CGImageRelease(partialImageRef);
  240. dispatch_main_sync_safe(^{
  241. if (self.completedBlock) {
  242. self.completedBlock(image, nil, nil, NO);
  243. }
  244. });
  245. }
  246. }
  247. CFRelease(imageSource);
  248. }
  249. if (self.progressBlock) {
  250. self.progressBlock(self.imageData.length, self.expectedSize);
  251. }
  252. }
  253. + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value {
  254. switch (value) {
  255. case 1:
  256. return UIImageOrientationUp;
  257. case 3:
  258. return UIImageOrientationDown;
  259. case 8:
  260. return UIImageOrientationLeft;
  261. case 6:
  262. return UIImageOrientationRight;
  263. case 2:
  264. return UIImageOrientationUpMirrored;
  265. case 4:
  266. return UIImageOrientationDownMirrored;
  267. case 5:
  268. return UIImageOrientationLeftMirrored;
  269. case 7:
  270. return UIImageOrientationRightMirrored;
  271. default:
  272. return UIImageOrientationUp;
  273. }
  274. }
  275. - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
  276. return EMSDScaledImageForKey(key, image);
  277. }
  278. - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
  279. EMSDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
  280. @synchronized(self) {
  281. CFRunLoopStop(CFRunLoopGetCurrent());
  282. self.thread = nil;
  283. self.connection = nil;
  284. [[NSNotificationCenter defaultCenter] postNotificationName:EMSDWebImageDownloadStopNotification object:nil];
  285. }
  286. if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) {
  287. responseFromCached = NO;
  288. }
  289. if (completionBlock)
  290. {
  291. if (self.options & EMSDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
  292. completionBlock(nil, nil, nil, YES);
  293. }
  294. else {
  295. UIImage *image = [UIImage sd_imageWithData:self.imageData];
  296. NSString *key = [[EMSDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
  297. image = [self scaledImageForKey:key image:image];
  298. // Do not force decoding animated GIFs
  299. if (!image.images) {
  300. image = [UIImage decodedImageWithImage:image];
  301. }
  302. if (CGSizeEqualToSize(image.size, CGSizeZero)) {
  303. completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
  304. }
  305. else {
  306. completionBlock(image, self.imageData, nil, YES);
  307. }
  308. }
  309. }
  310. self.completionBlock = nil;
  311. [self done];
  312. }
  313. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  314. CFRunLoopStop(CFRunLoopGetCurrent());
  315. [[NSNotificationCenter defaultCenter] postNotificationName:EMSDWebImageDownloadStopNotification object:nil];
  316. if (self.completedBlock) {
  317. self.completedBlock(nil, nil, error, YES);
  318. }
  319. [self done];
  320. }
  321. - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
  322. responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
  323. if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
  324. // Prevents caching of responses
  325. return nil;
  326. }
  327. else {
  328. return cachedResponse;
  329. }
  330. }
  331. - (BOOL)shouldContinueWhenAppEntersBackground {
  332. return self.options & EMSDWebImageDownloaderContinueInBackground;
  333. }
  334. - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
  335. return self.shouldUseCredentialStorage;
  336. }
  337. - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
  338. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  339. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  340. [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  341. } else {
  342. if ([challenge previousFailureCount] == 0) {
  343. if (self.credential) {
  344. [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
  345. } else {
  346. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  347. }
  348. } else {
  349. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  350. }
  351. }
  352. }
  353. @end