├── .gitignore ├── LICENSE ├── README.md ├── plugin.xml ├── src ├── android │ └── CollectionRepeatImage.java └── ios │ ├── CollectionRepeatImage.h │ ├── CollectionRepeatImage.m │ ├── NSData+ImageContentType.h │ ├── NSData+ImageContentType.m │ ├── SDImageCache.h │ ├── SDImageCache.m │ ├── SDWebImageCompat.h │ ├── SDWebImageCompat.m │ ├── SDWebImageDecoder.h │ ├── SDWebImageDecoder.m │ ├── SDWebImageDownloader.h │ ├── SDWebImageDownloader.m │ ├── SDWebImageDownloaderOperation.h │ ├── SDWebImageDownloaderOperation.m │ ├── SDWebImageManager.h │ ├── SDWebImageManager.m │ ├── SDWebImageOperation.h │ ├── SDWebImagePrefetcher.h │ ├── SDWebImagePrefetcher.m │ ├── UIImage+GIF.h │ ├── UIImage+GIF.m │ ├── UIImage+MultiFormat.h │ ├── UIImage+MultiFormat.m │ ├── UIImage+ResizeMagick.h │ ├── UIImage+ResizeMagick.m │ ├── UIImage+WebP.h │ ├── UIImage+WebP.m │ ├── UIImageView+WebCache.h │ ├── UIImageView+WebCache.m │ ├── UIView+WebCacheOperation.h │ └── UIView+WebCacheOperation.m └── www ├── CollectionRepeatImage.js └── CollectionRepeatImageOptions.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 - Mallzee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Collection Repeat Image 2 | 3 | Making performant scrolling lists in hybrid apps is very difficult. There are a few decent attempts to fix this problem. [IonicFramework Collection Repeat](http://ionicframework.com/docs/api/directive/collectionRepeat/) being the best we've used so far, [Including our own attempt](https://github.com/mallzee/angular-ui-table-view). 4 | 5 | When you do not control the source of the images for these lists you start to get problems when scaling massive images on the main javascript thread. This can lead to crazy jankyness on older phones and newer if the images are massive. 6 | 7 | This plugin offloads the image processing to native land to download the image and scale it to the desired size in a background thread. When everything is ready a base64 string of the image is sent back to javascript land to be injected into the img tag. 8 | 9 | It's essentially a wrapper around SDWebImage optimised to work with Ionic's collection repeat 10 | 11 | ```JavaScript 12 | var image = document.getElementById('scaled-image'); 13 | var rect = image.getBoundingClientRect(); 14 | 15 | var options = { 16 | data: src, 17 | index: scope.id, 18 | quality: 0, 19 | scale: Math.round(rect.width) + 'x' + Math.round(rect.height), 20 | downloadOptions: window.CollectionRepeatImageOptions.SDWebImageCacheMemoryOnly | window.CollectionRepeatImageOptions.SDWebImageLowPriority 21 | }; 22 | 23 | window.CollectionRepeatImage.getImage(options, function (data) { 24 | image.src = 'data:image/jpeg;base64,' + data; 25 | }); 26 | ``` 27 | 28 | ## Installation 29 | 30 | cordova plugin add https://github.com/mallzee/cordova-collection-repeat-image-plugin.git 31 | 32 | ## Supported Platforms 33 | 34 | - iOS 35 | - Android (Soon) 36 | 37 | ## API 38 | 39 | - window.CollectionRepeatImage.getImage(options, success, failure) 40 | - window.CollectionRepeatImage.cancel(index) 41 | - window.CollectionRepeatImage.cancelAll() 42 | 43 | ### options 44 | 45 | - url: The url for the specified image 46 | - index: The index associated with this image. Used to cancel jobs when items have gone out of view 47 | - quality: [0 - 1] The compression applied to the image. 48 | - scale: The image magic format "[width]x[height]" See [here](https://github.com/mustangostang/UIImage-ResizeMagick) for more variations 49 | - downloadOptions: Bit mask of options to apply to the download. See [Download Options](https://github.com/mallzee/cordova-collection-repeat-image-plugin#download-options) 50 | 51 | ### Download Options 52 | 53 | #### window.CollectionRepeatImageOptions.SDWebImageRetryFailed 54 | 55 | By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. This flag disable this blacklisting. 56 | 57 | #### window.CollectionRepeatImageOptions.SDWebImageLowPriority 58 | 59 | By default, image downloads are started during UI interactions, this flags disable this feature, leading to delayed download on UIScrollView deceleration for instance. 60 | 61 | #### window.CollectionRepeatImageOptions.SDWebImageCacheMemoryOnly 62 | 63 | This flag disables on-disk caching 64 | 65 | #### window.CollectionRepeatImageOptions.SDWebImageProgressiveDownload 66 | 67 | This flag enables progressive download, the image is displayed progressively during download as a browser would do. By default, the image is only displayed once completely downloaded. 68 | 69 | #### window.CollectionRepeatImageOptions.SDWebImageRefreshCached 70 | 71 | Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 72 | 73 | *Use this flag only if you can't make your URLs static with embedded cache busting parameter.* 74 | 75 | #### window.CollectionRepeatImageOptions.SDWebImageContinueInBackground 76 | 77 | In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for extra time in background to let the request finish. If the background task expires the operation will be cancelled. 78 | 79 | #### window.CollectionRepeatImageOptions.SDWebImageHandleCookies, 80 | 81 | Handles cookies stored in NSHTTPCookieStore by setting NSMutableURLRequest.HTTPShouldHandleCookies = YES; 82 | 83 | 84 | #### window.CollectionRepeatImageOptions.SDWebImageAllowInvalidSSLCertificates 85 | 86 | Enable to allow untrusted SSL certificates. Useful for testing purposes. Use with caution in production. 87 | 88 | #### window.CollectionRepeatImageOptions.SDWebImageHighPriority 89 | 90 | By default, image are loaded in the order they were queued. This flag move them to the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which could take a while). 91 | 92 | #### window.CollectionRepeatImageOptions.SDWebImageDelayPlaceholder 93 | 94 | By default, placeholder images are loaded while the image is loading. This flag will delay the loading of the placeholder image until after the image has finished loading. 95 | 96 | ## Sample Angular Directive 97 | 98 | Example of the markup inside of a collection repeat. 99 | 100 | ```HTML 101 |
102 | 103 |
104 |
105 | ``` 106 | 107 | Example directive to make use of the plugin. 108 | 109 | ```JavaScript 110 | angular.directive('mlzImg', ['$animate', function ($animate) { 111 | return { 112 | restrict: 'E', 113 | scope: { 114 | src: '@', 115 | id: '@' 116 | }, 117 | template: '', 118 | link: function (scope, element) { 119 | 120 | var image = element.children(), 121 | hasLoader = false, 122 | hasLoaded = false, 123 | rect; 124 | 125 | function getDimensions() { 126 | if (!rect) { 127 | rect = element[0].getBoundingClientRect(); 128 | } 129 | return rect; 130 | } 131 | 132 | if (!hasLoader) { 133 | image.on('load', function () { 134 | ionic.requestAnimationFrame(function () { 135 | $animate.addClass(image[0], 'fade-in-not-out'); 136 | }); 137 | hasLoaded = true; 138 | }).on('error', function () { 139 | // TODO: Have some default error image 140 | }); 141 | hasLoader = true; 142 | } 143 | 144 | function replaceWithScaledImage(src, rect) { 145 | if (ionic.Platform.isWebView()) { 146 | var options = { 147 | data: src, 148 | index: scope.id, 149 | quality: 1, 150 | options: window.CollectionRepeatImageOptions.SDWebImageCacheMemoryOnly, 151 | scale: (Math.round(rect.width) * 2) + 'x' + (Math.round(rect.height) * 2)// + '#' // Uncomment to crop and scale 152 | }; 153 | 154 | window.CollectionRepeatImage.getImage(options, function (data) { 155 | image[0].src = 'data:image/jpeg;base64,' + data; 156 | }, function (error) { 157 | // TODO: Place broken image stuff in 158 | console.log('Resize error', error); 159 | }); 160 | } else { 161 | image[0].src = src; 162 | } 163 | } 164 | 165 | function loadNewImage(src) { 166 | ionic.requestAnimationFrame(function () { 167 | image[0].classList.remove('fade-in-not-out'); 168 | replaceWithScaledImage(src, getDimensions()); 169 | }); 170 | } 171 | 172 | scope.$watch('src', function (src, oldSrc) { 173 | if (src && rect && src !== oldSrc || !hasLoaded) { 174 | if (ionic.Platform.isWebView()) { 175 | window.CollectionRepeatImage.cancel(scope.id); 176 | loadNewImage(src); 177 | } else { 178 | loadNewImage(src); 179 | } 180 | } 181 | }); 182 | } 183 | }; 184 | }); 185 | ``` 186 | 187 | Cancel all operations on a scope destroy 188 | 189 | ```JavaScript 190 | $scope.$on('destroy', function () { 191 | if(ionic.Platform.isWebView()) { 192 | cordova.plugins.CollectionRepeatImage.cancelAll() 193 | } 194 | }); 195 | ``` 196 | 197 | ## Attribution 198 | 199 | - [SDWebImage](https://github.com/rs/SDWebImage) 200 | - [UIImage-ResizeMagick](https://github.com/mustangostang/UIImage-ResizeMagick) 201 | -------------------------------------------------------------------------------- /plugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | CollectionRepeatImage 4 | Offloads image scaling to a background thread to releave pressure on the JavaScript thread 5 | Mallzee 6 | MIT 7 | image,collection,repeat,sdwebimage,webimage 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /src/android/CollectionRepeatImage.java: -------------------------------------------------------------------------------- 1 | package com.mallzee.collectionrepeatimage; 2 | 3 | import org.apache.cordova.CordovaPlugin; 4 | import org.apache.cordova.CallbackContext; 5 | 6 | import org.json.JSONArray; 7 | import org.json.JSONException; 8 | import org.json.JSONObject; 9 | 10 | /** 11 | * This class echoes a string called from JavaScript. 12 | */ 13 | public class CollectionRepeatImage extends CordovaPlugin { 14 | 15 | @Override 16 | public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { 17 | if (action.equals("getImage")) { 18 | String message = args.getString(0); 19 | this.getImage(message, callbackContext); 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | private void getImage(String message, CallbackContext callbackContext) { 26 | if (message != null && message.length() > 0) { 27 | callbackContext.success(message); 28 | } else { 29 | callbackContext.error("Expected one non-empty string argument."); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/ios/CollectionRepeatImage.h: -------------------------------------------------------------------------------- 1 | // 2 | // CollectionRepeatImage.h 3 | // Mallzee 4 | // 5 | // Created by Jamie Sutherland on 24/10/2014. 6 | // 7 | // 8 | 9 | #ifndef Mallzee_CollectionRepeatImage_h 10 | #define Mallzee_CollectionRepeatImage_h 11 | 12 | #import 13 | #import "UIImageView+WebCache.h" 14 | 15 | @interface CollectionRepeatImage : CDVPlugin { 16 | NSDictionary *options; 17 | NSMutableDictionary *indexes; 18 | SDWebImageManager *manager; 19 | } 20 | 21 | - (void)getImage:(CDVInvokedUrlCommand*)command; 22 | - (void)cancel: (CDVInvokedUrlCommand*)command; 23 | - (void)cancelAll: (CDVInvokedUrlCommand*)command; 24 | 25 | @end 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /src/ios/CollectionRepeatImage.m: -------------------------------------------------------------------------------- 1 | /********* CDVCollectionRepeatImage.m Cordova Plugin Implementation *******/ 2 | 3 | #import "CollectionRepeatImage.h" 4 | #import "UIImage+ResizeMagick.h" 5 | 6 | @implementation CollectionRepeatImage 7 | 8 | // Setup the index and download manager 9 | - (void)pluginInitialize { 10 | indexes = [NSMutableDictionary new]; 11 | manager = [SDWebImageManager sharedManager]; 12 | SDWebImageManager.sharedManager.delegate = self; 13 | } 14 | 15 | // When we get the image. Scale it to the size that we asked for 16 | -(UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL 17 | { 18 | return [image resizedImageByMagick:[options objectForKey:@"scale"]]; 19 | } 20 | 21 | - (void)getImage:(CDVInvokedUrlCommand*)command 22 | { 23 | 24 | options = [command.arguments objectAtIndex:0]; 25 | NSString *index = [options objectForKey:@"index"]; 26 | 27 | // Setup the cache key so it considereds the scale asked for as well as the URL 28 | __weak __typeof(self) weakSelf = self; 29 | [manager setCacheKeyFilter:^(NSURL *url) { 30 | // Crazy referencing to stop seg faults when threaded 31 | __strong __typeof(self) strongSelf = weakSelf; 32 | return [NSString stringWithFormat:@"%@-%@", [url absoluteString], [strongSelf->options objectForKey:@"scale"]]; 33 | }]; 34 | 35 | // Set off a download job 36 | NSOperation *job = [manager downloadImageWithURL:[options objectForKey:@"data"] options:[[options objectForKey:@"downloadOptions"] integerValue] progress:^(NSInteger receivedSize, NSInteger expectedSize) 37 | { 38 | // TODO: create a callback so we can have a process update in web land 39 | } 40 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) 41 | { 42 | if (image) 43 | { 44 | // If we have an image. Switch it to a base64 image and send it back to web land to be injected 45 | NSString *base64Image = [UIImageJPEGRepresentation(image, [[options objectForKey:@"quality"] floatValue]) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 46 | 47 | CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:base64Image]; 48 | [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; 49 | } else { 50 | [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR]; 51 | } 52 | }]; 53 | 54 | // If we've specified an index. Record the job incase we need to cancel it 55 | if (index) { 56 | [indexes setValue:job forKey:index]; 57 | } 58 | } 59 | 60 | // Cancel a job at the specified index 61 | - (void)cancel:(CDVInvokedUrlCommand *)command 62 | { 63 | // Cancel the job if the index has changed 64 | NSString *index = [command.arguments objectAtIndex:0]; 65 | if (index) { 66 | NSOperation *job = [indexes objectForKey:index]; 67 | if (job) { 68 | [job cancel]; 69 | } 70 | } 71 | } 72 | 73 | // Cancel all the current job. Handy when you're leaving the view and want to stop everything. 74 | - (void)cancelAll:(CDVInvokedUrlCommand *)command 75 | { 76 | // Cancel all the current jobs 77 | [manager cancelAll]; 78 | } 79 | 80 | @end -------------------------------------------------------------------------------- /src/ios/NSData+ImageContentType.h: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import 7 | 8 | @interface NSData (ImageContentType) 9 | 10 | /** 11 | * Compute the content type for an image data 12 | * 13 | * @param data the input data 14 | * 15 | * @return the content type as string (i.e. image/jpeg, image/gif) 16 | */ 17 | + (NSString *)sd_contentTypeForImageData:(NSData *)data; 18 | 19 | @end 20 | 21 | 22 | @interface NSData (ImageContentTypeDeprecated) 23 | 24 | + (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`"); 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /src/ios/NSData+ImageContentType.m: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Fabrice Aneche on 06/01/14. 3 | // Copyright (c) 2014 Dailymotion. All rights reserved. 4 | // 5 | 6 | #import "NSData+ImageContentType.h" 7 | 8 | 9 | @implementation NSData (ImageContentType) 10 | 11 | + (NSString *)sd_contentTypeForImageData:(NSData *)data { 12 | uint8_t c; 13 | [data getBytes:&c length:1]; 14 | switch (c) { 15 | case 0xFF: 16 | return @"image/jpeg"; 17 | case 0x89: 18 | return @"image/png"; 19 | case 0x47: 20 | return @"image/gif"; 21 | case 0x49: 22 | case 0x4D: 23 | return @"image/tiff"; 24 | case 0x52: 25 | // R as RIFF for WEBP 26 | if ([data length] < 12) { 27 | return nil; 28 | } 29 | 30 | NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding]; 31 | if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) { 32 | return @"image/webp"; 33 | } 34 | 35 | return nil; 36 | } 37 | return nil; 38 | } 39 | 40 | @end 41 | 42 | 43 | @implementation NSData (ImageContentTypeDeprecated) 44 | 45 | + (NSString *)contentTypeForImageData:(NSData *)data { 46 | return [self sd_contentTypeForImageData:data]; 47 | } 48 | 49 | @end 50 | -------------------------------------------------------------------------------- /src/ios/SDImageCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | 12 | typedef NS_ENUM(NSInteger, SDImageCacheType) { 13 | /** 14 | * The image wasn't available the SDWebImage caches, but was downloaded from the web. 15 | */ 16 | SDImageCacheTypeNone, 17 | /** 18 | * The image was obtained from the disk cache. 19 | */ 20 | SDImageCacheTypeDisk, 21 | /** 22 | * The image was obtained from the memory cache. 23 | */ 24 | SDImageCacheTypeMemory 25 | }; 26 | 27 | typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType); 28 | 29 | typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); 30 | 31 | typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); 32 | 33 | /** 34 | * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed 35 | * asynchronous so it doesn’t add unnecessary latency to the UI. 36 | */ 37 | @interface SDImageCache : NSObject 38 | 39 | /** 40 | * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. 41 | */ 42 | @property (assign, nonatomic) NSUInteger maxMemoryCost; 43 | 44 | /** 45 | * The maximum length of time to keep an image in the cache, in seconds 46 | */ 47 | @property (assign, nonatomic) NSInteger maxCacheAge; 48 | 49 | /** 50 | * The maximum size of the cache, in bytes. 51 | */ 52 | @property (assign, nonatomic) NSUInteger maxCacheSize; 53 | 54 | /** 55 | * Returns global shared cache instance 56 | * 57 | * @return SDImageCache global instance 58 | */ 59 | + (SDImageCache *)sharedImageCache; 60 | 61 | /** 62 | * Init a new cache store with a specific namespace 63 | * 64 | * @param ns The namespace to use for this cache store 65 | */ 66 | - (id)initWithNamespace:(NSString *)ns; 67 | 68 | /** 69 | * Add a read-only cache path to search for images pre-cached by SDImageCache 70 | * Useful if you want to bundle pre-loaded images with your app 71 | * 72 | * @param path The path to use for this read-only cache path 73 | */ 74 | - (void)addReadOnlyCachePath:(NSString *)path; 75 | 76 | /** 77 | * Store an image into memory and disk cache at the given key. 78 | * 79 | * @param image The image to store 80 | * @param key The unique image cache key, usually it's image absolute URL 81 | */ 82 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key; 83 | 84 | /** 85 | * Store an image into memory and optionally disk cache at the given key. 86 | * 87 | * @param image The image to store 88 | * @param key The unique image cache key, usually it's image absolute URL 89 | * @param toDisk Store the image to disk cache if YES 90 | */ 91 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk; 92 | 93 | /** 94 | * Store an image into memory and optionally disk cache at the given key. 95 | * 96 | * @param image The image to store 97 | * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage 98 | * @param imageData The image data as returned by the server, this representation will be used for disk storage 99 | * instead of converting the given image object into a storable/compressed image format in order 100 | * to save quality and CPU 101 | * @param key The unique image cache key, usually it's image absolute URL 102 | * @param toDisk Store the image to disk cache if YES 103 | */ 104 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk; 105 | 106 | /** 107 | * Query the disk cache asynchronously. 108 | * 109 | * @param key The unique key used to store the wanted image 110 | */ 111 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock; 112 | 113 | /** 114 | * Query the memory cache synchronously. 115 | * 116 | * @param key The unique key used to store the wanted image 117 | */ 118 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key; 119 | 120 | /** 121 | * Query the disk cache synchronously after checking the memory cache. 122 | * 123 | * @param key The unique key used to store the wanted image 124 | */ 125 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key; 126 | 127 | /** 128 | * Remove the image from memory and disk cache synchronously 129 | * 130 | * @param key The unique image cache key 131 | */ 132 | - (void)removeImageForKey:(NSString *)key; 133 | 134 | 135 | /** 136 | * Remove the image from memory and disk cache synchronously 137 | * 138 | * @param key The unique image cache key 139 | * @param completionBlock An block that should be executed after the image has been removed (optional) 140 | */ 141 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion; 142 | 143 | /** 144 | * Remove the image from memory and optionally disk cache synchronously 145 | * 146 | * @param key The unique image cache key 147 | * @param fromDisk Also remove cache entry from disk if YES 148 | */ 149 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk; 150 | 151 | /** 152 | * Remove the image from memory and optionally disk cache synchronously 153 | * 154 | * @param key The unique image cache key 155 | * @param fromDisk Also remove cache entry from disk if YES 156 | * @param completionBlock An block that should be executed after the image has been removed (optional) 157 | */ 158 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion; 159 | 160 | /** 161 | * Clear all memory cached images 162 | */ 163 | - (void)clearMemory; 164 | 165 | /** 166 | * Clear all disk cached images. Non-blocking method - returns immediately. 167 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 168 | */ 169 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion; 170 | 171 | /** 172 | * Clear all disk cached images 173 | * @see clearDiskOnCompletion: 174 | */ 175 | - (void)clearDisk; 176 | 177 | /** 178 | * Remove all expired cached image from disk. Non-blocking method - returns immediately. 179 | * @param completionBlock An block that should be executed after cache expiration completes (optional) 180 | */ 181 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock; 182 | 183 | /** 184 | * Remove all expired cached image from disk 185 | * @see cleanDiskWithCompletionBlock: 186 | */ 187 | - (void)cleanDisk; 188 | 189 | /** 190 | * Get the size used by the disk cache 191 | */ 192 | - (NSUInteger)getSize; 193 | 194 | /** 195 | * Get the number of images in the disk cache 196 | */ 197 | - (NSUInteger)getDiskCount; 198 | 199 | /** 200 | * Asynchronously calculate the disk cache's size. 201 | */ 202 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock; 203 | 204 | /** 205 | * Async check if image exists in disk cache already (does not load the image) 206 | * 207 | * @param key the key describing the url 208 | * @param completionBlock the block to be executed when the check is done. 209 | * @note the completion block will be always executed on the main queue 210 | */ 211 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 212 | 213 | /** 214 | * Check if image exists in disk cache already (does not load the image) 215 | * 216 | * @param key the key describing the url 217 | * 218 | * @return YES if an image exists for the given key 219 | */ 220 | - (BOOL)diskImageExistsWithKey:(NSString *)key; 221 | 222 | /** 223 | * Get the cache path for a certain key (needs the cache path root folder) 224 | * 225 | * @param key the key (can be obtained from url using cacheKeyForURL) 226 | * @param path the cach path root folder 227 | * 228 | * @return the cache path 229 | */ 230 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path; 231 | 232 | /** 233 | * Get the default cache path for a certain key 234 | * 235 | * @param key the key (can be obtained from url using cacheKeyForURL) 236 | * 237 | * @return the default cache path 238 | */ 239 | - (NSString *)defaultCachePathForKey:(NSString *)key; 240 | 241 | @end 242 | -------------------------------------------------------------------------------- /src/ios/SDImageCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDImageCache.h" 10 | #import "SDWebImageDecoder.h" 11 | #import "UIImage+MultiFormat.h" 12 | #import 13 | 14 | static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week 15 | // PNG signature bytes and data (below) 16 | static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; 17 | static NSData *kPNGSignatureData = nil; 18 | 19 | BOOL ImageDataHasPNGPreffix(NSData *data); 20 | 21 | BOOL ImageDataHasPNGPreffix(NSData *data) { 22 | NSUInteger pngSignatureLength = [kPNGSignatureData length]; 23 | if ([data length] >= pngSignatureLength) { 24 | if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) { 25 | return YES; 26 | } 27 | } 28 | 29 | return NO; 30 | } 31 | 32 | @interface SDImageCache () 33 | 34 | @property (strong, nonatomic) NSCache *memCache; 35 | @property (strong, nonatomic) NSString *diskCachePath; 36 | @property (strong, nonatomic) NSMutableArray *customPaths; 37 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue; 38 | 39 | @end 40 | 41 | 42 | @implementation SDImageCache { 43 | NSFileManager *_fileManager; 44 | } 45 | 46 | + (SDImageCache *)sharedImageCache { 47 | static dispatch_once_t once; 48 | static id instance; 49 | dispatch_once(&once, ^{ 50 | instance = [self new]; 51 | kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8]; 52 | }); 53 | return instance; 54 | } 55 | 56 | - (id)init { 57 | return [self initWithNamespace:@"default"]; 58 | } 59 | 60 | - (id)initWithNamespace:(NSString *)ns { 61 | if ((self = [super init])) { 62 | NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; 63 | 64 | // Create IO serial queue 65 | _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); 66 | 67 | // Init default values 68 | _maxCacheAge = kDefaultCacheMaxCacheAge; 69 | 70 | // Init the memory cache 71 | _memCache = [[NSCache alloc] init]; 72 | _memCache.name = fullNamespace; 73 | 74 | // Init the disk cache 75 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 76 | _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace]; 77 | 78 | dispatch_sync(_ioQueue, ^{ 79 | _fileManager = [NSFileManager new]; 80 | }); 81 | 82 | #if TARGET_OS_IPHONE 83 | // Subscribe to app events 84 | [[NSNotificationCenter defaultCenter] addObserver:self 85 | selector:@selector(clearMemory) 86 | name:UIApplicationDidReceiveMemoryWarningNotification 87 | object:nil]; 88 | 89 | [[NSNotificationCenter defaultCenter] addObserver:self 90 | selector:@selector(cleanDisk) 91 | name:UIApplicationWillTerminateNotification 92 | object:nil]; 93 | 94 | [[NSNotificationCenter defaultCenter] addObserver:self 95 | selector:@selector(backgroundCleanDisk) 96 | name:UIApplicationDidEnterBackgroundNotification 97 | object:nil]; 98 | #endif 99 | } 100 | 101 | return self; 102 | } 103 | 104 | - (void)dealloc { 105 | [[NSNotificationCenter defaultCenter] removeObserver:self]; 106 | SDDispatchQueueRelease(_ioQueue); 107 | } 108 | 109 | - (void)addReadOnlyCachePath:(NSString *)path { 110 | if (!self.customPaths) { 111 | self.customPaths = [NSMutableArray new]; 112 | } 113 | 114 | if (![self.customPaths containsObject:path]) { 115 | [self.customPaths addObject:path]; 116 | } 117 | } 118 | 119 | - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path { 120 | NSString *filename = [self cachedFileNameForKey:key]; 121 | return [path stringByAppendingPathComponent:filename]; 122 | } 123 | 124 | - (NSString *)defaultCachePathForKey:(NSString *)key { 125 | return [self cachePathForKey:key inPath:self.diskCachePath]; 126 | } 127 | 128 | #pragma mark SDImageCache (private) 129 | 130 | - (NSString *)cachedFileNameForKey:(NSString *)key { 131 | const char *str = [key UTF8String]; 132 | if (str == NULL) { 133 | str = ""; 134 | } 135 | unsigned char r[CC_MD5_DIGEST_LENGTH]; 136 | CC_MD5(str, (CC_LONG)strlen(str), r); 137 | NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 138 | r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]]; 139 | 140 | return filename; 141 | } 142 | 143 | #pragma mark ImageCache 144 | 145 | - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk { 146 | if (!image || !key) { 147 | return; 148 | } 149 | 150 | [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale]; 151 | 152 | if (toDisk) { 153 | dispatch_async(self.ioQueue, ^{ 154 | NSData *data = imageData; 155 | 156 | if (image && (recalculate || !data)) { 157 | #if TARGET_OS_IPHONE 158 | // We need to determine if the image is a PNG or a JPEG 159 | // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html) 160 | // The first eight bytes of a PNG file always contain the following (decimal) values: 161 | // 137 80 78 71 13 10 26 10 162 | 163 | // We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly), 164 | // we will consider it PNG to avoid loosing the transparency 165 | BOOL imageIsPng = YES; 166 | 167 | // But if we have an image data, we will look at the preffix 168 | if ([imageData length] >= [kPNGSignatureData length]) { 169 | imageIsPng = ImageDataHasPNGPreffix(imageData); 170 | } 171 | 172 | if (imageIsPng) { 173 | data = UIImagePNGRepresentation(image); 174 | } 175 | else { 176 | data = UIImageJPEGRepresentation(image, (CGFloat)1.0); 177 | } 178 | #else 179 | data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil]; 180 | #endif 181 | } 182 | 183 | if (data) { 184 | if (![_fileManager fileExistsAtPath:_diskCachePath]) { 185 | [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; 186 | } 187 | 188 | [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil]; 189 | } 190 | }); 191 | } 192 | } 193 | 194 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key { 195 | [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES]; 196 | } 197 | 198 | - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk { 199 | [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk]; 200 | } 201 | 202 | - (BOOL)diskImageExistsWithKey:(NSString *)key { 203 | BOOL exists = NO; 204 | 205 | // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance 206 | // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely. 207 | exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]]; 208 | 209 | return exists; 210 | } 211 | 212 | - (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 213 | dispatch_async(_ioQueue, ^{ 214 | BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; 215 | if (completionBlock) { 216 | dispatch_async(dispatch_get_main_queue(), ^{ 217 | completionBlock(exists); 218 | }); 219 | } 220 | }); 221 | } 222 | 223 | - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key { 224 | return [self.memCache objectForKey:key]; 225 | } 226 | 227 | - (UIImage *)imageFromDiskCacheForKey:(NSString *)key { 228 | // First check the in-memory cache... 229 | UIImage *image = [self imageFromMemoryCacheForKey:key]; 230 | if (image) { 231 | return image; 232 | } 233 | 234 | // Second check the disk cache... 235 | UIImage *diskImage = [self diskImageForKey:key]; 236 | if (diskImage) { 237 | CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; 238 | [self.memCache setObject:diskImage forKey:key cost:cost]; 239 | } 240 | 241 | return diskImage; 242 | } 243 | 244 | - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key { 245 | NSString *defaultPath = [self defaultCachePathForKey:key]; 246 | NSData *data = [NSData dataWithContentsOfFile:defaultPath]; 247 | if (data) { 248 | return data; 249 | } 250 | 251 | for (NSString *path in self.customPaths) { 252 | NSString *filePath = [self cachePathForKey:key inPath:path]; 253 | NSData *imageData = [NSData dataWithContentsOfFile:filePath]; 254 | if (imageData) { 255 | return imageData; 256 | } 257 | } 258 | 259 | return nil; 260 | } 261 | 262 | - (UIImage *)diskImageForKey:(NSString *)key { 263 | NSData *data = [self diskImageDataBySearchingAllPathsForKey:key]; 264 | if (data) { 265 | UIImage *image = [UIImage sd_imageWithData:data]; 266 | image = [self scaledImageForKey:key image:image]; 267 | image = [UIImage decodedImageWithImage:image]; 268 | return image; 269 | } 270 | else { 271 | return nil; 272 | } 273 | } 274 | 275 | - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { 276 | return SDScaledImageForKey(key, image); 277 | } 278 | 279 | - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock { 280 | if (!doneBlock) { 281 | return nil; 282 | } 283 | 284 | if (!key) { 285 | doneBlock(nil, SDImageCacheTypeNone); 286 | return nil; 287 | } 288 | 289 | // First check the in-memory cache... 290 | UIImage *image = [self imageFromMemoryCacheForKey:key]; 291 | if (image) { 292 | doneBlock(image, SDImageCacheTypeMemory); 293 | return nil; 294 | } 295 | 296 | NSOperation *operation = [NSOperation new]; 297 | dispatch_async(self.ioQueue, ^{ 298 | if (operation.isCancelled) { 299 | return; 300 | } 301 | 302 | @autoreleasepool { 303 | UIImage *diskImage = [self diskImageForKey:key]; 304 | if (diskImage) { 305 | CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale; 306 | [self.memCache setObject:diskImage forKey:key cost:cost]; 307 | } 308 | 309 | dispatch_async(dispatch_get_main_queue(), ^{ 310 | doneBlock(diskImage, SDImageCacheTypeDisk); 311 | }); 312 | } 313 | }); 314 | 315 | return operation; 316 | } 317 | 318 | - (void)removeImageForKey:(NSString *)key { 319 | [self removeImageForKey:key withCompletion:nil]; 320 | } 321 | 322 | - (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion { 323 | [self removeImageForKey:key fromDisk:YES withCompletion:completion]; 324 | } 325 | 326 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk { 327 | [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil]; 328 | } 329 | 330 | - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion { 331 | 332 | if (key == nil) { 333 | return; 334 | } 335 | 336 | [self.memCache removeObjectForKey:key]; 337 | 338 | if (fromDisk) { 339 | dispatch_async(self.ioQueue, ^{ 340 | [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; 341 | 342 | if (completion) { 343 | dispatch_async(dispatch_get_main_queue(), ^{ 344 | completion(); 345 | }); 346 | } 347 | }); 348 | } else if (completion){ 349 | completion(); 350 | } 351 | 352 | } 353 | 354 | - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { 355 | self.memCache.totalCostLimit = maxMemoryCost; 356 | } 357 | 358 | - (NSUInteger)maxMemoryCost { 359 | return self.memCache.totalCostLimit; 360 | } 361 | 362 | - (void)clearMemory { 363 | [self.memCache removeAllObjects]; 364 | } 365 | 366 | - (void)clearDisk { 367 | [self clearDiskOnCompletion:nil]; 368 | } 369 | 370 | - (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion 371 | { 372 | dispatch_async(self.ioQueue, ^{ 373 | [_fileManager removeItemAtPath:self.diskCachePath error:nil]; 374 | [_fileManager createDirectoryAtPath:self.diskCachePath 375 | withIntermediateDirectories:YES 376 | attributes:nil 377 | error:NULL]; 378 | 379 | if (completion) { 380 | dispatch_async(dispatch_get_main_queue(), ^{ 381 | completion(); 382 | }); 383 | } 384 | }); 385 | } 386 | 387 | - (void)cleanDisk { 388 | [self cleanDiskWithCompletionBlock:nil]; 389 | } 390 | 391 | - (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock { 392 | dispatch_async(self.ioQueue, ^{ 393 | NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; 394 | NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]; 395 | 396 | // This enumerator prefetches useful properties for our cache files. 397 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL 398 | includingPropertiesForKeys:resourceKeys 399 | options:NSDirectoryEnumerationSkipsHiddenFiles 400 | errorHandler:NULL]; 401 | 402 | NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge]; 403 | NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; 404 | NSUInteger currentCacheSize = 0; 405 | 406 | // Enumerate all of the files in the cache directory. This loop has two purposes: 407 | // 408 | // 1. Removing files that are older than the expiration date. 409 | // 2. Storing file attributes for the size-based cleanup pass. 410 | NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; 411 | for (NSURL *fileURL in fileEnumerator) { 412 | NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL]; 413 | 414 | // Skip directories. 415 | if ([resourceValues[NSURLIsDirectoryKey] boolValue]) { 416 | continue; 417 | } 418 | 419 | // Remove files that are older than the expiration date; 420 | NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey]; 421 | if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) { 422 | [urlsToDelete addObject:fileURL]; 423 | continue; 424 | } 425 | 426 | // Store a reference to this file and account for its total size. 427 | NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; 428 | currentCacheSize += [totalAllocatedSize unsignedIntegerValue]; 429 | [cacheFiles setObject:resourceValues forKey:fileURL]; 430 | } 431 | 432 | for (NSURL *fileURL in urlsToDelete) { 433 | [_fileManager removeItemAtURL:fileURL error:nil]; 434 | } 435 | 436 | // If our remaining disk cache exceeds a configured maximum size, perform a second 437 | // size-based cleanup pass. We delete the oldest files first. 438 | if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) { 439 | // Target half of our maximum cache size for this cleanup pass. 440 | const NSUInteger desiredCacheSize = self.maxCacheSize / 2; 441 | 442 | // Sort the remaining cache files by their last modification time (oldest first). 443 | NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent 444 | usingComparator:^NSComparisonResult(id obj1, id obj2) { 445 | return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; 446 | }]; 447 | 448 | // Delete files until we fall below our desired cache size. 449 | for (NSURL *fileURL in sortedFiles) { 450 | if ([_fileManager removeItemAtURL:fileURL error:nil]) { 451 | NSDictionary *resourceValues = cacheFiles[fileURL]; 452 | NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey]; 453 | currentCacheSize -= [totalAllocatedSize unsignedIntegerValue]; 454 | 455 | if (currentCacheSize < desiredCacheSize) { 456 | break; 457 | } 458 | } 459 | } 460 | } 461 | if (completionBlock) { 462 | dispatch_async(dispatch_get_main_queue(), ^{ 463 | completionBlock(); 464 | }); 465 | } 466 | }); 467 | } 468 | 469 | - (void)backgroundCleanDisk { 470 | UIApplication *application = [UIApplication sharedApplication]; 471 | __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ 472 | // Clean up any unfinished task business by marking where you 473 | // stopped or ending the task outright. 474 | [application endBackgroundTask:bgTask]; 475 | bgTask = UIBackgroundTaskInvalid; 476 | }]; 477 | 478 | // Start the long-running task and return immediately. 479 | [self cleanDiskWithCompletionBlock:^{ 480 | [application endBackgroundTask:bgTask]; 481 | bgTask = UIBackgroundTaskInvalid; 482 | }]; 483 | } 484 | 485 | - (NSUInteger)getSize { 486 | __block NSUInteger size = 0; 487 | dispatch_sync(self.ioQueue, ^{ 488 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; 489 | for (NSString *fileName in fileEnumerator) { 490 | NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName]; 491 | NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil]; 492 | size += [attrs fileSize]; 493 | } 494 | }); 495 | return size; 496 | } 497 | 498 | - (NSUInteger)getDiskCount { 499 | __block NSUInteger count = 0; 500 | dispatch_sync(self.ioQueue, ^{ 501 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath]; 502 | count = [[fileEnumerator allObjects] count]; 503 | }); 504 | return count; 505 | } 506 | 507 | - (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock { 508 | NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; 509 | 510 | dispatch_async(self.ioQueue, ^{ 511 | NSUInteger fileCount = 0; 512 | NSUInteger totalSize = 0; 513 | 514 | NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL 515 | includingPropertiesForKeys:@[NSFileSize] 516 | options:NSDirectoryEnumerationSkipsHiddenFiles 517 | errorHandler:NULL]; 518 | 519 | for (NSURL *fileURL in fileEnumerator) { 520 | NSNumber *fileSize; 521 | [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; 522 | totalSize += [fileSize unsignedIntegerValue]; 523 | fileCount += 1; 524 | } 525 | 526 | if (completionBlock) { 527 | dispatch_async(dispatch_get_main_queue(), ^{ 528 | completionBlock(fileCount, totalSize); 529 | }); 530 | } 531 | }); 532 | } 533 | 534 | @end 535 | -------------------------------------------------------------------------------- /src/ios/SDWebImageCompat.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * (c) Jamie Pinkham 5 | * 6 | * For the full copyright and license information, please view the LICENSE 7 | * file that was distributed with this source code. 8 | */ 9 | 10 | #import 11 | 12 | #ifdef __OBJC_GC__ 13 | #error SDWebImage does not support Objective-C Garbage Collection 14 | #endif 15 | 16 | #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 17 | #error SDWebImage doesn't support Deployement Target version < 5.0 18 | #endif 19 | 20 | #if !TARGET_OS_IPHONE 21 | #import 22 | #ifndef UIImage 23 | #define UIImage NSImage 24 | #endif 25 | #ifndef UIImageView 26 | #define UIImageView NSImageView 27 | #endif 28 | #else 29 | 30 | #import 31 | 32 | #endif 33 | 34 | #ifndef NS_ENUM 35 | #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type 36 | #endif 37 | 38 | #ifndef NS_OPTIONS 39 | #define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type 40 | #endif 41 | 42 | #if OS_OBJECT_USE_OBJC 43 | #undef SDDispatchQueueRelease 44 | #undef SDDispatchQueueSetterSementics 45 | #define SDDispatchQueueRelease(q) 46 | #define SDDispatchQueueSetterSementics strong 47 | #else 48 | #undef SDDispatchQueueRelease 49 | #undef SDDispatchQueueSetterSementics 50 | #define SDDispatchQueueRelease(q) (dispatch_release(q)) 51 | #define SDDispatchQueueSetterSementics assign 52 | #endif 53 | 54 | extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image); 55 | 56 | typedef void(^SDWebImageNoParamsBlock)(); 57 | 58 | #define dispatch_main_sync_safe(block)\ 59 | if ([NSThread isMainThread]) {\ 60 | block();\ 61 | } else {\ 62 | dispatch_sync(dispatch_get_main_queue(), block);\ 63 | } 64 | 65 | #define dispatch_main_async_safe(block)\ 66 | if ([NSThread isMainThread]) {\ 67 | block();\ 68 | } else {\ 69 | dispatch_async(dispatch_get_main_queue(), block);\ 70 | } 71 | -------------------------------------------------------------------------------- /src/ios/SDWebImageCompat.m: -------------------------------------------------------------------------------- 1 | // 2 | // SDWebImageCompat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 11/12/12. 6 | // Copyright (c) 2012 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "SDWebImageCompat.h" 10 | 11 | #if !__has_feature(objc_arc) 12 | #error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag 13 | #endif 14 | 15 | inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) { 16 | if (!image) { 17 | return nil; 18 | } 19 | 20 | if ([image.images count] > 0) { 21 | NSMutableArray *scaledImages = [NSMutableArray array]; 22 | 23 | for (UIImage *tempImage in image.images) { 24 | [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; 25 | } 26 | 27 | return [UIImage animatedImageWithImages:scaledImages duration:image.duration]; 28 | } 29 | else { 30 | if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { 31 | CGFloat scale = 1.0; 32 | if (key.length >= 8) { 33 | // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext) 34 | NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)]; 35 | if (range.location != NSNotFound) { 36 | scale = 2.0; 37 | } 38 | } 39 | 40 | UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; 41 | image = scaledImage; 42 | } 43 | return image; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import 12 | #import "SDWebImageCompat.h" 13 | 14 | @interface UIImage (ForceDecode) 15 | 16 | + (UIImage *)decodedImageWithImage:(UIImage *)image; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDecoder.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * Created by james on 9/28/11. 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | #import "SDWebImageDecoder.h" 12 | 13 | @implementation UIImage (ForceDecode) 14 | 15 | + (UIImage *)decodedImageWithImage:(UIImage *)image { 16 | if (image.images) { 17 | // Do not decode animated images 18 | return image; 19 | } 20 | 21 | CGImageRef imageRef = image.CGImage; 22 | CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef)); 23 | CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize}; 24 | 25 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 26 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 27 | 28 | int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask); 29 | BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone || 30 | infoMask == kCGImageAlphaNoneSkipFirst || 31 | infoMask == kCGImageAlphaNoneSkipLast); 32 | 33 | // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. 34 | // https://developer.apple.com/library/mac/#qa/qa1037/_index.html 35 | if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) { 36 | // Unset the old alpha info. 37 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 38 | 39 | // Set noneSkipFirst. 40 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 41 | } 42 | // Some PNGs tell us they have alpha but only 3 components. Odd. 43 | else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { 44 | // Unset the old alpha info. 45 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 46 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 47 | } 48 | 49 | // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. 50 | CGContextRef context = CGBitmapContextCreate(NULL, 51 | imageSize.width, 52 | imageSize.height, 53 | CGImageGetBitsPerComponent(imageRef), 54 | 0, 55 | colorSpace, 56 | bitmapInfo); 57 | CGColorSpaceRelease(colorSpace); 58 | 59 | // If failed, return undecompressed image 60 | if (!context) return image; 61 | 62 | CGContextDrawImage(context, imageRect, imageRef); 63 | CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context); 64 | 65 | CGContextRelease(context); 66 | 67 | UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation]; 68 | CGImageRelease(decompressedImageRef); 69 | return decompressedImage; 70 | } 71 | 72 | @end 73 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDownloader.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageCompat.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) { 14 | SDWebImageDownloaderLowPriority = 1 << 0, 15 | SDWebImageDownloaderProgressiveDownload = 1 << 1, 16 | 17 | /** 18 | * By default, request prevent the of NSURLCache. With this flag, NSURLCache 19 | * is used with default policies. 20 | */ 21 | SDWebImageDownloaderUseNSURLCache = 1 << 2, 22 | 23 | /** 24 | * Call completion block with nil image/imageData if the image was read from NSURLCache 25 | * (to be combined with `SDWebImageDownloaderUseNSURLCache`). 26 | */ 27 | 28 | SDWebImageDownloaderIgnoreCachedResponse = 1 << 3, 29 | /** 30 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 31 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 32 | */ 33 | 34 | SDWebImageDownloaderContinueInBackground = 1 << 4, 35 | 36 | /** 37 | * Handles cookies stored in NSHTTPCookieStore by setting 38 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 39 | */ 40 | SDWebImageDownloaderHandleCookies = 1 << 5, 41 | 42 | /** 43 | * Enable to allow untrusted SSL ceriticates. 44 | * Useful for testing purposes. Use with caution in production. 45 | */ 46 | SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6, 47 | 48 | /** 49 | * Put the image in the high priority queue. 50 | */ 51 | SDWebImageDownloaderHighPriority = 1 << 7, 52 | 53 | 54 | }; 55 | 56 | typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) { 57 | /** 58 | * Default value. All download operations will execute in queue style (first-in-first-out). 59 | */ 60 | SDWebImageDownloaderFIFOExecutionOrder, 61 | 62 | /** 63 | * All download operations will execute in stack style (last-in-first-out). 64 | */ 65 | SDWebImageDownloaderLIFOExecutionOrder 66 | }; 67 | 68 | extern NSString *const SDWebImageDownloadStartNotification; 69 | extern NSString *const SDWebImageDownloadStopNotification; 70 | 71 | typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 72 | 73 | typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished); 74 | 75 | typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers); 76 | 77 | /** 78 | * Asynchronous downloader dedicated and optimized for image loading. 79 | */ 80 | @interface SDWebImageDownloader : NSObject 81 | 82 | @property (assign, nonatomic) NSInteger maxConcurrentDownloads; 83 | 84 | /** 85 | * Shows the current amount of downloads that still need to be downloaded 86 | */ 87 | 88 | @property (readonly, nonatomic) NSUInteger currentDownloadCount; 89 | 90 | 91 | /** 92 | * The timeout value (in seconds) for the download operation. Default: 15.0. 93 | */ 94 | @property (assign, nonatomic) NSTimeInterval downloadTimeout; 95 | 96 | 97 | /** 98 | * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. 99 | */ 100 | @property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; 101 | 102 | /** 103 | * Singleton method, returns the shared instance 104 | * 105 | * @return global shared instance of downloader class 106 | */ 107 | + (SDWebImageDownloader *)sharedDownloader; 108 | 109 | /** 110 | * Set username 111 | */ 112 | @property (strong, nonatomic) NSString *username; 113 | 114 | /** 115 | * Set password 116 | */ 117 | @property (strong, nonatomic) NSString *password; 118 | 119 | /** 120 | * Set filter to pick headers for downloading image HTTP request. 121 | * 122 | * This block will be invoked for each downloading image request, returned 123 | * NSDictionary will be used as headers in corresponding HTTP request. 124 | */ 125 | @property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter; 126 | 127 | /** 128 | * Set a value for a HTTP header to be appended to each download HTTP request. 129 | * 130 | * @param value The value for the header field. Use `nil` value to remove the header. 131 | * @param field The name of the header field to set. 132 | */ 133 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field; 134 | 135 | /** 136 | * Returns the value of the specified HTTP header field. 137 | * 138 | * @return The value associated with the header field field, or `nil` if there is no corresponding header field. 139 | */ 140 | - (NSString *)valueForHTTPHeaderField:(NSString *)field; 141 | 142 | /** 143 | * Creates a SDWebImageDownloader async downloader instance with a given URL 144 | * 145 | * The delegate will be informed when the image is finish downloaded or an error has happen. 146 | * 147 | * @see SDWebImageDownloaderDelegate 148 | * 149 | * @param url The URL to the image to download 150 | * @param options The options to be used for this download 151 | * @param progressBlock A block called repeatedly while the image is downloading 152 | * @param completedBlock A block called once the download is completed. 153 | * If the download succeeded, the image parameter is set, in case of error, 154 | * error parameter is set with the error. The last parameter is always YES 155 | * if SDWebImageDownloaderProgressiveDownload isn't use. With the 156 | * SDWebImageDownloaderProgressiveDownload option, this block is called 157 | * repeatedly with the partial image object and the finished argument set to NO 158 | * before to be called a last time with the full image and finished argument 159 | * set to YES. In case of error, the finished argument is always YES. 160 | * 161 | * @return A cancellable SDWebImageOperation 162 | */ 163 | - (id )downloadImageWithURL:(NSURL *)url 164 | options:(SDWebImageDownloaderOptions)options 165 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 166 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock; 167 | 168 | /** 169 | * Sets the download queue suspension state 170 | */ 171 | - (void)setSuspended:(BOOL)suspended; 172 | 173 | @end 174 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDownloader.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageDownloader.h" 10 | #import "SDWebImageDownloaderOperation.h" 11 | #import 12 | 13 | NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; 14 | NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; 15 | 16 | static NSString *const kProgressCallbackKey = @"progress"; 17 | static NSString *const kCompletedCallbackKey = @"completed"; 18 | 19 | @interface SDWebImageDownloader () 20 | 21 | @property (strong, nonatomic) NSOperationQueue *downloadQueue; 22 | @property (weak, nonatomic) NSOperation *lastAddedOperation; 23 | @property (strong, nonatomic) NSMutableDictionary *URLCallbacks; 24 | @property (strong, nonatomic) NSMutableDictionary *HTTPHeaders; 25 | // This queue is used to serialize the handling of the network responses of all the download operation in a single queue 26 | @property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue; 27 | 28 | @end 29 | 30 | @implementation SDWebImageDownloader 31 | 32 | + (void)initialize { 33 | // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator ) 34 | // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import 35 | if (NSClassFromString(@"SDNetworkActivityIndicator")) { 36 | 37 | #pragma clang diagnostic push 38 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 39 | id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")]; 40 | #pragma clang diagnostic pop 41 | 42 | // Remove observer in case it was previously added. 43 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil]; 44 | [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil]; 45 | 46 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 47 | selector:NSSelectorFromString(@"startActivity") 48 | name:SDWebImageDownloadStartNotification object:nil]; 49 | [[NSNotificationCenter defaultCenter] addObserver:activityIndicator 50 | selector:NSSelectorFromString(@"stopActivity") 51 | name:SDWebImageDownloadStopNotification object:nil]; 52 | } 53 | } 54 | 55 | + (SDWebImageDownloader *)sharedDownloader { 56 | static dispatch_once_t once; 57 | static id instance; 58 | dispatch_once(&once, ^{ 59 | instance = [self new]; 60 | }); 61 | return instance; 62 | } 63 | 64 | - (id)init { 65 | if ((self = [super init])) { 66 | _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; 67 | _downloadQueue = [NSOperationQueue new]; 68 | _downloadQueue.maxConcurrentOperationCount = 2; 69 | _URLCallbacks = [NSMutableDictionary new]; 70 | _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"]; 71 | _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT); 72 | _downloadTimeout = 15.0; 73 | } 74 | return self; 75 | } 76 | 77 | - (void)dealloc { 78 | [self.downloadQueue cancelAllOperations]; 79 | SDDispatchQueueRelease(_barrierQueue); 80 | } 81 | 82 | - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field { 83 | if (value) { 84 | self.HTTPHeaders[field] = value; 85 | } 86 | else { 87 | [self.HTTPHeaders removeObjectForKey:field]; 88 | } 89 | } 90 | 91 | - (NSString *)valueForHTTPHeaderField:(NSString *)field { 92 | return self.HTTPHeaders[field]; 93 | } 94 | 95 | - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { 96 | _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; 97 | } 98 | 99 | - (NSUInteger)currentDownloadCount { 100 | return _downloadQueue.operationCount; 101 | } 102 | 103 | - (NSInteger)maxConcurrentDownloads { 104 | return _downloadQueue.maxConcurrentOperationCount; 105 | } 106 | 107 | - (id )downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock { 108 | __block SDWebImageDownloaderOperation *operation; 109 | __weak SDWebImageDownloader *wself = self; 110 | 111 | [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{ 112 | NSTimeInterval timeoutInterval = wself.downloadTimeout; 113 | if (timeoutInterval == 0.0) { 114 | timeoutInterval = 15.0; 115 | } 116 | 117 | // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise 118 | NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval]; 119 | request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); 120 | request.HTTPShouldUsePipelining = YES; 121 | if (wself.headersFilter) { 122 | request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]); 123 | } 124 | else { 125 | request.allHTTPHeaderFields = wself.HTTPHeaders; 126 | } 127 | operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request 128 | options:options 129 | progress:^(NSInteger receivedSize, NSInteger expectedSize) { 130 | SDWebImageDownloader *sself = wself; 131 | if (!sself) return; 132 | NSArray *callbacksForURL = [sself callbacksForURL:url]; 133 | for (NSDictionary *callbacks in callbacksForURL) { 134 | SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey]; 135 | if (callback) callback(receivedSize, expectedSize); 136 | } 137 | } 138 | completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { 139 | SDWebImageDownloader *sself = wself; 140 | if (!sself) return; 141 | NSArray *callbacksForURL = [sself callbacksForURL:url]; 142 | if (finished) { 143 | [sself removeCallbacksForURL:url]; 144 | } 145 | for (NSDictionary *callbacks in callbacksForURL) { 146 | SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey]; 147 | if (callback) callback(image, data, error, finished); 148 | } 149 | } 150 | cancelled:^{ 151 | SDWebImageDownloader *sself = wself; 152 | if (!sself) return; 153 | [sself removeCallbacksForURL:url]; 154 | }]; 155 | 156 | if (wself.username && wself.password) { 157 | operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession]; 158 | } 159 | 160 | if (options & SDWebImageDownloaderHighPriority) { 161 | operation.queuePriority = NSOperationQueuePriorityHigh; 162 | } else if (options & SDWebImageDownloaderLowPriority) { 163 | operation.queuePriority = NSOperationQueuePriorityLow; 164 | } 165 | 166 | [wself.downloadQueue addOperation:operation]; 167 | if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { 168 | // Emulate LIFO execution order by systematically adding new operations as last operation's dependency 169 | [wself.lastAddedOperation addDependency:operation]; 170 | wself.lastAddedOperation = operation; 171 | } 172 | }]; 173 | 174 | return operation; 175 | } 176 | 177 | - (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback { 178 | // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data. 179 | if (url == nil) { 180 | if (completedBlock != nil) { 181 | completedBlock(nil, nil, nil, NO); 182 | } 183 | return; 184 | } 185 | 186 | dispatch_barrier_sync(self.barrierQueue, ^{ 187 | BOOL first = NO; 188 | if (!self.URLCallbacks[url]) { 189 | self.URLCallbacks[url] = [NSMutableArray new]; 190 | first = YES; 191 | } 192 | 193 | // Handle single download of simultaneous download request for the same URL 194 | NSMutableArray *callbacksForURL = self.URLCallbacks[url]; 195 | NSMutableDictionary *callbacks = [NSMutableDictionary new]; 196 | if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy]; 197 | if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy]; 198 | [callbacksForURL addObject:callbacks]; 199 | self.URLCallbacks[url] = callbacksForURL; 200 | 201 | if (first) { 202 | createCallback(); 203 | } 204 | }); 205 | } 206 | 207 | - (NSArray *)callbacksForURL:(NSURL *)url { 208 | __block NSArray *callbacksForURL; 209 | dispatch_sync(self.barrierQueue, ^{ 210 | callbacksForURL = self.URLCallbacks[url]; 211 | }); 212 | return [callbacksForURL copy]; 213 | } 214 | 215 | - (void)removeCallbacksForURL:(NSURL *)url { 216 | dispatch_barrier_async(self.barrierQueue, ^{ 217 | [self.URLCallbacks removeObjectForKey:url]; 218 | }); 219 | } 220 | 221 | - (void)setSuspended:(BOOL)suspended { 222 | [self.downloadQueue setSuspended:suspended]; 223 | } 224 | 225 | @end 226 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDownloaderOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageDownloader.h" 11 | #import "SDWebImageOperation.h" 12 | 13 | @interface SDWebImageDownloaderOperation : NSOperation 14 | 15 | /** 16 | * The request used by the operation's connection. 17 | */ 18 | @property (strong, nonatomic, readonly) NSURLRequest *request; 19 | 20 | /** 21 | * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. 22 | * 23 | * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. 24 | */ 25 | @property (nonatomic, assign) BOOL shouldUseCredentialStorage; 26 | 27 | /** 28 | * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. 29 | * 30 | * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. 31 | */ 32 | @property (nonatomic, strong) NSURLCredential *credential; 33 | 34 | /** 35 | * The SDWebImageDownloaderOptions for the receiver. 36 | */ 37 | @property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; 38 | 39 | /** 40 | * Initializes a `SDWebImageDownloaderOperation` object 41 | * 42 | * @see SDWebImageDownloaderOperation 43 | * 44 | * @param request the URL request 45 | * @param options downloader options 46 | * @param progressBlock the block executed when a new chunk of data arrives. 47 | * @note the progress block is executed on a background queue 48 | * @param completedBlock the block executed when the download is done. 49 | * @note the completed block is executed on the main queue for success. If errors are found, there is a chance the block will be executed on a background queue 50 | * @param cancelBlock the block executed if the download (operation) is cancelled 51 | * 52 | * @return the initialized instance 53 | */ 54 | - (id)initWithRequest:(NSURLRequest *)request 55 | options:(SDWebImageDownloaderOptions)options 56 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 57 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 58 | cancelled:(SDWebImageNoParamsBlock)cancelBlock; 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /src/ios/SDWebImageDownloaderOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageDownloaderOperation.h" 10 | #import "SDWebImageDecoder.h" 11 | #import "UIImage+MultiFormat.h" 12 | #import 13 | #import "SDWebImageManager.h" 14 | 15 | @interface SDWebImageDownloaderOperation () 16 | 17 | @property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock; 18 | @property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock; 19 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; 20 | 21 | @property (assign, nonatomic, getter = isExecuting) BOOL executing; 22 | @property (assign, nonatomic, getter = isFinished) BOOL finished; 23 | @property (assign, nonatomic) NSInteger expectedSize; 24 | @property (strong, nonatomic) NSMutableData *imageData; 25 | @property (strong, nonatomic) NSURLConnection *connection; 26 | @property (strong, atomic) NSThread *thread; 27 | 28 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 29 | @property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; 30 | #endif 31 | 32 | @end 33 | 34 | @implementation SDWebImageDownloaderOperation { 35 | size_t width, height; 36 | UIImageOrientation orientation; 37 | BOOL responseFromCached; 38 | } 39 | 40 | @synthesize executing = _executing; 41 | @synthesize finished = _finished; 42 | 43 | - (id)initWithRequest:(NSURLRequest *)request 44 | options:(SDWebImageDownloaderOptions)options 45 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 46 | completed:(SDWebImageDownloaderCompletedBlock)completedBlock 47 | cancelled:(SDWebImageNoParamsBlock)cancelBlock { 48 | if ((self = [super init])) { 49 | _request = request; 50 | _shouldUseCredentialStorage = YES; 51 | _options = options; 52 | _progressBlock = [progressBlock copy]; 53 | _completedBlock = [completedBlock copy]; 54 | _cancelBlock = [cancelBlock copy]; 55 | _executing = NO; 56 | _finished = NO; 57 | _expectedSize = 0; 58 | responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called 59 | } 60 | return self; 61 | } 62 | 63 | - (void)start { 64 | @synchronized (self) { 65 | if (self.isCancelled) { 66 | self.finished = YES; 67 | [self reset]; 68 | return; 69 | } 70 | 71 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 72 | if ([self shouldContinueWhenAppEntersBackground]) { 73 | __weak __typeof__ (self) wself = self; 74 | self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 75 | __strong __typeof (wself) sself = wself; 76 | 77 | if (sself) { 78 | [sself cancel]; 79 | 80 | [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId]; 81 | sself.backgroundTaskId = UIBackgroundTaskInvalid; 82 | } 83 | }]; 84 | } 85 | #endif 86 | 87 | self.executing = YES; 88 | self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; 89 | self.thread = [NSThread currentThread]; 90 | } 91 | 92 | [self.connection start]; 93 | 94 | if (self.connection) { 95 | if (self.progressBlock) { 96 | self.progressBlock(0, NSURLResponseUnknownLength); 97 | } 98 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self]; 99 | 100 | if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) { 101 | // Make sure to run the runloop in our background thread so it can process downloaded data 102 | // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5 103 | // not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466) 104 | CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false); 105 | } 106 | else { 107 | CFRunLoopRun(); 108 | } 109 | 110 | if (!self.isFinished) { 111 | [self.connection cancel]; 112 | [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]]; 113 | } 114 | } 115 | else { 116 | if (self.completedBlock) { 117 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES); 118 | } 119 | } 120 | 121 | #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 122 | if (self.backgroundTaskId != UIBackgroundTaskInvalid) { 123 | [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId]; 124 | self.backgroundTaskId = UIBackgroundTaskInvalid; 125 | } 126 | #endif 127 | } 128 | 129 | - (void)cancel { 130 | @synchronized (self) { 131 | if (self.thread) { 132 | [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO]; 133 | } 134 | else { 135 | [self cancelInternal]; 136 | } 137 | } 138 | } 139 | 140 | - (void)cancelInternalAndStop { 141 | if (self.isFinished) return; 142 | [self cancelInternal]; 143 | CFRunLoopStop(CFRunLoopGetCurrent()); 144 | } 145 | 146 | - (void)cancelInternal { 147 | if (self.isFinished) return; 148 | [super cancel]; 149 | if (self.cancelBlock) self.cancelBlock(); 150 | 151 | if (self.connection) { 152 | [self.connection cancel]; 153 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self]; 154 | 155 | // As we cancelled the connection, its callback won't be called and thus won't 156 | // maintain the isFinished and isExecuting flags. 157 | if (self.isExecuting) self.executing = NO; 158 | if (!self.isFinished) self.finished = YES; 159 | } 160 | 161 | [self reset]; 162 | } 163 | 164 | - (void)done { 165 | self.finished = YES; 166 | self.executing = NO; 167 | [self reset]; 168 | } 169 | 170 | - (void)reset { 171 | self.cancelBlock = nil; 172 | self.completedBlock = nil; 173 | self.progressBlock = nil; 174 | self.connection = nil; 175 | self.imageData = nil; 176 | self.thread = nil; 177 | } 178 | 179 | - (void)setFinished:(BOOL)finished { 180 | [self willChangeValueForKey:@"isFinished"]; 181 | _finished = finished; 182 | [self didChangeValueForKey:@"isFinished"]; 183 | } 184 | 185 | - (void)setExecuting:(BOOL)executing { 186 | [self willChangeValueForKey:@"isExecuting"]; 187 | _executing = executing; 188 | [self didChangeValueForKey:@"isExecuting"]; 189 | } 190 | 191 | - (BOOL)isConcurrent { 192 | return YES; 193 | } 194 | 195 | #pragma mark NSURLConnection (delegate) 196 | 197 | - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 198 | if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) { 199 | NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0; 200 | self.expectedSize = expected; 201 | if (self.progressBlock) { 202 | self.progressBlock(0, expected); 203 | } 204 | 205 | self.imageData = [[NSMutableData alloc] initWithCapacity:expected]; 206 | } 207 | else { 208 | [self.connection cancel]; 209 | 210 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 211 | 212 | if (self.completedBlock) { 213 | self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES); 214 | } 215 | CFRunLoopStop(CFRunLoopGetCurrent()); 216 | [self done]; 217 | } 218 | } 219 | 220 | - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 221 | [self.imageData appendData:data]; 222 | 223 | if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) { 224 | // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ 225 | // Thanks to the author @Nyx0uf 226 | 227 | // Get the total bytes downloaded 228 | const NSInteger totalSize = self.imageData.length; 229 | 230 | // Update the data source, we must pass ALL the data, not just the new bytes 231 | CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL); 232 | CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize); 233 | 234 | if (width + height == 0) { 235 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 236 | if (properties) { 237 | NSInteger orientationValue = -1; 238 | CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight); 239 | if (val) CFNumberGetValue(val, kCFNumberLongType, &height); 240 | val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth); 241 | if (val) CFNumberGetValue(val, kCFNumberLongType, &width); 242 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 243 | if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue); 244 | CFRelease(properties); 245 | 246 | // When we draw to Core Graphics, we lose orientation information, 247 | // which means the image below born of initWithCGIImage will be 248 | // oriented incorrectly sometimes. (Unlike the image born of initWithData 249 | // in connectionDidFinishLoading.) So save it here and pass it on later. 250 | orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)]; 251 | } 252 | 253 | } 254 | 255 | if (width + height > 0 && totalSize < self.expectedSize) { 256 | // Create the image 257 | CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL); 258 | 259 | #ifdef TARGET_OS_IPHONE 260 | // Workaround for iOS anamorphic image 261 | if (partialImageRef) { 262 | const size_t partialHeight = CGImageGetHeight(partialImageRef); 263 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 264 | CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst); 265 | CGColorSpaceRelease(colorSpace); 266 | if (bmContext) { 267 | CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef); 268 | CGImageRelease(partialImageRef); 269 | partialImageRef = CGBitmapContextCreateImage(bmContext); 270 | CGContextRelease(bmContext); 271 | } 272 | else { 273 | CGImageRelease(partialImageRef); 274 | partialImageRef = nil; 275 | } 276 | } 277 | #endif 278 | 279 | if (partialImageRef) { 280 | UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation]; 281 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; 282 | UIImage *scaledImage = [self scaledImageForKey:key image:image]; 283 | image = [UIImage decodedImageWithImage:scaledImage]; 284 | CGImageRelease(partialImageRef); 285 | dispatch_main_sync_safe(^{ 286 | if (self.completedBlock) { 287 | self.completedBlock(image, nil, nil, NO); 288 | } 289 | }); 290 | } 291 | } 292 | 293 | CFRelease(imageSource); 294 | } 295 | 296 | if (self.progressBlock) { 297 | self.progressBlock(self.imageData.length, self.expectedSize); 298 | } 299 | } 300 | 301 | + (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value { 302 | switch (value) { 303 | case 1: 304 | return UIImageOrientationUp; 305 | case 3: 306 | return UIImageOrientationDown; 307 | case 8: 308 | return UIImageOrientationLeft; 309 | case 6: 310 | return UIImageOrientationRight; 311 | case 2: 312 | return UIImageOrientationUpMirrored; 313 | case 4: 314 | return UIImageOrientationDownMirrored; 315 | case 5: 316 | return UIImageOrientationLeftMirrored; 317 | case 7: 318 | return UIImageOrientationRightMirrored; 319 | default: 320 | return UIImageOrientationUp; 321 | } 322 | } 323 | 324 | - (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image { 325 | return SDScaledImageForKey(key, image); 326 | } 327 | 328 | - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection { 329 | SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock; 330 | @synchronized(self) { 331 | CFRunLoopStop(CFRunLoopGetCurrent()); 332 | self.thread = nil; 333 | self.connection = nil; 334 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 335 | } 336 | 337 | if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) { 338 | responseFromCached = NO; 339 | } 340 | 341 | if (completionBlock) 342 | { 343 | if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) { 344 | completionBlock(nil, nil, nil, YES); 345 | } 346 | else { 347 | UIImage *image = [UIImage sd_imageWithData:self.imageData]; 348 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; 349 | image = [self scaledImageForKey:key image:image]; 350 | 351 | // Do not force decoding animated GIFs 352 | if (!image.images) { 353 | image = [UIImage decodedImageWithImage:image]; 354 | } 355 | if (CGSizeEqualToSize(image.size, CGSizeZero)) { 356 | completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES); 357 | } 358 | else { 359 | completionBlock(image, self.imageData, nil, YES); 360 | } 361 | } 362 | } 363 | self.completionBlock = nil; 364 | [self done]; 365 | } 366 | 367 | - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 368 | CFRunLoopStop(CFRunLoopGetCurrent()); 369 | [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil]; 370 | 371 | if (self.completedBlock) { 372 | self.completedBlock(nil, nil, error, YES); 373 | } 374 | 375 | [self done]; 376 | } 377 | 378 | - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { 379 | responseFromCached = NO; // If this method is called, it means the response wasn't read from cache 380 | if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) { 381 | // Prevents caching of responses 382 | return nil; 383 | } 384 | else { 385 | return cachedResponse; 386 | } 387 | } 388 | 389 | - (BOOL)shouldContinueWhenAppEntersBackground { 390 | return self.options & SDWebImageDownloaderContinueInBackground; 391 | } 392 | 393 | - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { 394 | return self.shouldUseCredentialStorage; 395 | } 396 | 397 | - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ 398 | if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 399 | NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 400 | [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 401 | } else { 402 | if ([challenge previousFailureCount] == 0) { 403 | if (self.credential) { 404 | [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; 405 | } else { 406 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 407 | } 408 | } else { 409 | [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; 410 | } 411 | } 412 | } 413 | 414 | @end 415 | -------------------------------------------------------------------------------- /src/ios/SDWebImageManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageOperation.h" 11 | #import "SDWebImageDownloader.h" 12 | #import "SDImageCache.h" 13 | 14 | typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) { 15 | /** 16 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 17 | * This flag disable this blacklisting. 18 | */ 19 | SDWebImageRetryFailed = 1 << 0, 20 | 21 | /** 22 | * By default, image downloads are started during UI interactions, this flags disable this feature, 23 | * leading to delayed download on UIScrollView deceleration for instance. 24 | */ 25 | SDWebImageLowPriority = 1 << 1, 26 | 27 | /** 28 | * This flag disables on-disk caching 29 | */ 30 | SDWebImageCacheMemoryOnly = 1 << 2, 31 | 32 | /** 33 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 34 | * By default, the image is only displayed once completely downloaded. 35 | */ 36 | SDWebImageProgressiveDownload = 1 << 3, 37 | 38 | /** 39 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 40 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 41 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 42 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 43 | * 44 | * Use this flag only if you can't make your URLs static with embeded cache busting parameter. 45 | */ 46 | SDWebImageRefreshCached = 1 << 4, 47 | 48 | /** 49 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 50 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 51 | */ 52 | SDWebImageContinueInBackground = 1 << 5, 53 | 54 | /** 55 | * Handles cookies stored in NSHTTPCookieStore by setting 56 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 57 | */ 58 | SDWebImageHandleCookies = 1 << 6, 59 | 60 | /** 61 | * Enable to allow untrusted SSL ceriticates. 62 | * Useful for testing purposes. Use with caution in production. 63 | */ 64 | SDWebImageAllowInvalidSSLCertificates = 1 << 7, 65 | 66 | /** 67 | * By default, image are loaded in the order they were queued. This flag move them to 68 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 69 | * could take a while). 70 | */ 71 | SDWebImageHighPriority = 1 << 8, 72 | 73 | /** 74 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 75 | * of the placeholder image until after the image has finished loading. 76 | */ 77 | SDWebImageDelayPlaceholder = 1 << 9 78 | }; 79 | 80 | typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL); 81 | 82 | typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL); 83 | 84 | typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url); 85 | 86 | 87 | @class SDWebImageManager; 88 | 89 | @protocol SDWebImageManagerDelegate 90 | 91 | @optional 92 | 93 | /** 94 | * Controls which image should be downloaded when the image is not found in the cache. 95 | * 96 | * @param imageManager The current `SDWebImageManager` 97 | * @param imageURL The url of the image to be downloaded 98 | * 99 | * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 100 | */ 101 | - (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL; 102 | 103 | /** 104 | * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 105 | * NOTE: This method is called from a global queue in order to not to block the main thread. 106 | * 107 | * @param imageManager The current `SDWebImageManager` 108 | * @param image The image to transform 109 | * @param imageURL The url of the image to transform 110 | * 111 | * @return The transformed image object. 112 | */ 113 | - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL; 114 | 115 | @end 116 | 117 | /** 118 | * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes. 119 | * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache). 120 | * You can use this class directly to benefit from web image downloading with caching in another context than 121 | * a UIView. 122 | * 123 | * Here is a simple example of how to use SDWebImageManager: 124 | * 125 | * @code 126 | 127 | SDWebImageManager *manager = [SDWebImageManager sharedManager]; 128 | [manager downloadWithURL:imageURL 129 | options:0 130 | progress:nil 131 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 132 | if (image) { 133 | // do something with image 134 | } 135 | }]; 136 | 137 | * @endcode 138 | */ 139 | @interface SDWebImageManager : NSObject 140 | 141 | @property (weak, nonatomic) id delegate; 142 | 143 | @property (strong, nonatomic, readonly) SDImageCache *imageCache; 144 | @property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader; 145 | 146 | /** 147 | * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can 148 | * be used to remove dynamic part of an image URL. 149 | * 150 | * The following example sets a filter in the application delegate that will remove any query-string from the 151 | * URL before to use it as a cache key: 152 | * 153 | * @code 154 | 155 | [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) { 156 | url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; 157 | return [url absoluteString]; 158 | }]; 159 | 160 | * @endcode 161 | */ 162 | @property (copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter; 163 | 164 | /** 165 | * Returns global SDWebImageManager instance. 166 | * 167 | * @return SDWebImageManager shared instance 168 | */ 169 | + (SDWebImageManager *)sharedManager; 170 | 171 | /** 172 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 173 | * 174 | * @param url The URL to the image 175 | * @param options A mask to specify options to use for this request 176 | * @param progressBlock A block called while image is downloading 177 | * @param completedBlock A block called when operation has been completed. 178 | * 179 | * This parameter is required. 180 | * 181 | * This block has no return value and takes the requested UIImage as first parameter. 182 | * In case of error the image parameter is nil and the second parameter may contain an NSError. 183 | * 184 | * The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache 185 | * or from the memory cache or from the network. 186 | * 187 | * The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 188 | * downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the 189 | * block is called a last time with the full image and the last parameter set to YES. 190 | * 191 | * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation 192 | */ 193 | - (id )downloadImageWithURL:(NSURL *)url 194 | options:(SDWebImageOptions)options 195 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 196 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock; 197 | 198 | /** 199 | * Saves image to cache for given URL 200 | * 201 | * @param image The image to cache 202 | * @param url The URL to the image 203 | * 204 | */ 205 | 206 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url; 207 | 208 | /** 209 | * Cancel all current opreations 210 | */ 211 | - (void)cancelAll; 212 | 213 | /** 214 | * Check one or more operations running 215 | */ 216 | - (BOOL)isRunning; 217 | 218 | /** 219 | * Check if image has already been cached 220 | * 221 | * @param url image url 222 | * 223 | * @return if the image was already cached 224 | */ 225 | - (BOOL)cachedImageExistsForURL:(NSURL *)url; 226 | 227 | /** 228 | * Check if image has already been cached on disk only 229 | * 230 | * @param url image url 231 | * 232 | * @return if the image was already cached (disk only) 233 | */ 234 | - (BOOL)diskImageExistsForURL:(NSURL *)url; 235 | 236 | /** 237 | * Async check if image has already been cached 238 | * 239 | * @param url image url 240 | * @param completionBlock the block to be executed when the check is finished 241 | * 242 | * @note the completion block is always executed on the main queue 243 | */ 244 | - (void)cachedImageExistsForURL:(NSURL *)url 245 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 246 | 247 | /** 248 | * Async check if image has already been cached on disk only 249 | * 250 | * @param url image url 251 | * @param completionBlock the block to be executed when the check is finished 252 | * 253 | * @note the completion block is always executed on the main queue 254 | */ 255 | - (void)diskImageExistsForURL:(NSURL *)url 256 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock; 257 | 258 | 259 | /** 260 | *Return the cache key for a given URL 261 | */ 262 | - (NSString *)cacheKeyForURL:(NSURL *)url; 263 | 264 | @end 265 | 266 | 267 | #pragma mark - Deprecated 268 | 269 | typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`"); 270 | typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`"); 271 | 272 | 273 | @interface SDWebImageManager (Deprecated) 274 | 275 | /** 276 | * Downloads the image at the given URL if not present in cache or return the cached version otherwise. 277 | * 278 | * @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:` 279 | */ 280 | - (id )downloadWithURL:(NSURL *)url 281 | options:(SDWebImageOptions)options 282 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 283 | completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`"); 284 | 285 | @end 286 | -------------------------------------------------------------------------------- /src/ios/SDWebImageManager.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageManager.h" 10 | #import 11 | 12 | @interface SDWebImageCombinedOperation : NSObject 13 | 14 | @property (assign, nonatomic, getter = isCancelled) BOOL cancelled; 15 | @property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock; 16 | @property (strong, nonatomic) NSOperation *cacheOperation; 17 | 18 | @end 19 | 20 | @interface SDWebImageManager () 21 | 22 | @property (strong, nonatomic, readwrite) SDImageCache *imageCache; 23 | @property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader; 24 | @property (strong, nonatomic) NSMutableArray *failedURLs; 25 | @property (strong, nonatomic) NSMutableArray *runningOperations; 26 | 27 | @end 28 | 29 | @implementation SDWebImageManager 30 | 31 | + (id)sharedManager { 32 | static dispatch_once_t once; 33 | static id instance; 34 | dispatch_once(&once, ^{ 35 | instance = [self new]; 36 | }); 37 | return instance; 38 | } 39 | 40 | - (id)init { 41 | if ((self = [super init])) { 42 | _imageCache = [self createCache]; 43 | _imageDownloader = [SDWebImageDownloader sharedDownloader]; 44 | _failedURLs = [NSMutableArray new]; 45 | _runningOperations = [NSMutableArray new]; 46 | } 47 | return self; 48 | } 49 | 50 | - (SDImageCache *)createCache { 51 | return [SDImageCache sharedImageCache]; 52 | } 53 | 54 | - (NSString *)cacheKeyForURL:(NSURL *)url { 55 | if (self.cacheKeyFilter) { 56 | return self.cacheKeyFilter(url); 57 | } 58 | else { 59 | return [url absoluteString]; 60 | } 61 | } 62 | 63 | - (BOOL)cachedImageExistsForURL:(NSURL *)url { 64 | NSString *key = [self cacheKeyForURL:url]; 65 | if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES; 66 | return [self.imageCache diskImageExistsWithKey:key]; 67 | } 68 | 69 | - (BOOL)diskImageExistsForURL:(NSURL *)url { 70 | NSString *key = [self cacheKeyForURL:url]; 71 | return [self.imageCache diskImageExistsWithKey:key]; 72 | } 73 | 74 | - (void)cachedImageExistsForURL:(NSURL *)url 75 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 76 | NSString *key = [self cacheKeyForURL:url]; 77 | 78 | BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); 79 | 80 | if (isInMemoryCache) { 81 | // making sure we call the completion block on the main queue 82 | dispatch_async(dispatch_get_main_queue(), ^{ 83 | if (completionBlock) { 84 | completionBlock(YES); 85 | } 86 | }); 87 | return; 88 | } 89 | 90 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 91 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 92 | if (completionBlock) { 93 | completionBlock(isInDiskCache); 94 | } 95 | }]; 96 | } 97 | 98 | - (void)diskImageExistsForURL:(NSURL *)url 99 | completion:(SDWebImageCheckCacheCompletionBlock)completionBlock { 100 | NSString *key = [self cacheKeyForURL:url]; 101 | 102 | [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { 103 | // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch 104 | if (completionBlock) { 105 | completionBlock(isInDiskCache); 106 | } 107 | }]; 108 | } 109 | 110 | - (id )downloadImageWithURL:(NSURL *)url 111 | options:(SDWebImageOptions)options 112 | progress:(SDWebImageDownloaderProgressBlock)progressBlock 113 | completed:(SDWebImageCompletionWithFinishedBlock)completedBlock { 114 | // Invoking this method without a completedBlock is pointless 115 | NSParameterAssert(completedBlock); 116 | 117 | // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't 118 | // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString. 119 | if ([url isKindOfClass:NSString.class]) { 120 | url = [NSURL URLWithString:(NSString *)url]; 121 | } 122 | 123 | // Prevents app crashing on argument type error like sending NSNull instead of NSURL 124 | if (![url isKindOfClass:NSURL.class]) { 125 | url = nil; 126 | } 127 | 128 | __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new]; 129 | __weak SDWebImageCombinedOperation *weakOperation = operation; 130 | 131 | BOOL isFailedUrl = NO; 132 | @synchronized (self.failedURLs) { 133 | isFailedUrl = [self.failedURLs containsObject:url]; 134 | } 135 | 136 | if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { 137 | dispatch_main_sync_safe(^{ 138 | NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]; 139 | completedBlock(nil, error, SDImageCacheTypeNone, YES, url); 140 | }); 141 | return operation; 142 | } 143 | 144 | @synchronized (self.runningOperations) { 145 | [self.runningOperations addObject:operation]; 146 | } 147 | NSString *key = [self cacheKeyForURL:url]; 148 | 149 | operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) { 150 | if (operation.isCancelled) { 151 | @synchronized (self.runningOperations) { 152 | [self.runningOperations removeObject:operation]; 153 | } 154 | 155 | return; 156 | } 157 | 158 | if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) { 159 | if (image && options & SDWebImageRefreshCached) { 160 | dispatch_main_sync_safe(^{ 161 | // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image 162 | // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server. 163 | completedBlock(image, nil, cacheType, YES, url); 164 | }); 165 | } 166 | 167 | // download if no image or requested to refresh anyway, and download allowed by delegate 168 | SDWebImageDownloaderOptions downloaderOptions = 0; 169 | if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; 170 | if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; 171 | if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache; 172 | if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground; 173 | if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies; 174 | if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates; 175 | if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority; 176 | if (image && options & SDWebImageRefreshCached) { 177 | // force progressive off if image already cached but forced refreshing 178 | downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; 179 | // ignore image read from NSURLCache if image if cached but force refreshing 180 | downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; 181 | } 182 | id subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) { 183 | if (weakOperation.isCancelled) { 184 | // Do nothing if the operation was cancelled 185 | // See #699 for more details 186 | // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data 187 | } 188 | else if (error) { 189 | dispatch_main_sync_safe(^{ 190 | if (!weakOperation.isCancelled) { 191 | completedBlock(nil, error, SDImageCacheTypeNone, finished, url); 192 | } 193 | }); 194 | 195 | if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) { 196 | @synchronized (self.failedURLs) { 197 | [self.failedURLs addObject:url]; 198 | } 199 | } 200 | } 201 | else { 202 | BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); 203 | 204 | if (options & SDWebImageRefreshCached && image && !downloadedImage) { 205 | // Image refresh hit the NSURLCache cache, do not call the completion block 206 | } 207 | // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it 208 | else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { 209 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 210 | UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; 211 | 212 | if (transformedImage && finished) { 213 | BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; 214 | [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk]; 215 | } 216 | 217 | dispatch_main_sync_safe(^{ 218 | if (!weakOperation.isCancelled) { 219 | completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url); 220 | } 221 | }); 222 | }); 223 | } 224 | else { 225 | if (downloadedImage && finished) { 226 | [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk]; 227 | } 228 | 229 | dispatch_main_sync_safe(^{ 230 | if (!weakOperation.isCancelled) { 231 | completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url); 232 | } 233 | }); 234 | } 235 | } 236 | 237 | if (finished) { 238 | @synchronized (self.runningOperations) { 239 | [self.runningOperations removeObject:operation]; 240 | } 241 | } 242 | }]; 243 | operation.cancelBlock = ^{ 244 | [subOperation cancel]; 245 | 246 | @synchronized (self.runningOperations) { 247 | [self.runningOperations removeObject:weakOperation]; 248 | } 249 | }; 250 | } 251 | else if (image) { 252 | dispatch_main_sync_safe(^{ 253 | if (!weakOperation.isCancelled) { 254 | completedBlock(image, nil, cacheType, YES, url); 255 | } 256 | }); 257 | @synchronized (self.runningOperations) { 258 | [self.runningOperations removeObject:operation]; 259 | } 260 | } 261 | else { 262 | // Image not in cache and download disallowed by delegate 263 | dispatch_main_sync_safe(^{ 264 | if (!weakOperation.isCancelled) { 265 | completedBlock(nil, nil, SDImageCacheTypeNone, YES, url); 266 | } 267 | }); 268 | @synchronized (self.runningOperations) { 269 | [self.runningOperations removeObject:operation]; 270 | } 271 | } 272 | }]; 273 | 274 | return operation; 275 | } 276 | 277 | - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url { 278 | if (image && url) { 279 | NSString *key = [self cacheKeyForURL:url]; 280 | [self.imageCache storeImage:image forKey:key toDisk:YES]; 281 | } 282 | } 283 | 284 | - (void)cancelAll { 285 | @synchronized (self.runningOperations) { 286 | [self.runningOperations makeObjectsPerformSelector:@selector(cancel)]; 287 | [self.runningOperations removeAllObjects]; 288 | } 289 | } 290 | 291 | - (BOOL)isRunning { 292 | return self.runningOperations.count > 0; 293 | } 294 | 295 | @end 296 | 297 | 298 | @implementation SDWebImageCombinedOperation 299 | 300 | - (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock { 301 | // check if the operation is already cancelled, then we just call the cancelBlock 302 | if (self.isCancelled) { 303 | if (cancelBlock) { 304 | cancelBlock(); 305 | } 306 | _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes 307 | } else { 308 | _cancelBlock = [cancelBlock copy]; 309 | } 310 | } 311 | 312 | - (void)cancel { 313 | self.cancelled = YES; 314 | if (self.cacheOperation) { 315 | [self.cacheOperation cancel]; 316 | self.cacheOperation = nil; 317 | } 318 | if (self.cancelBlock) { 319 | self.cancelBlock(); 320 | 321 | // TODO: this is a temporary fix to #809. 322 | // Until we can figure the exact cause of the crash, going with the ivar instead of the setter 323 | // self.cancelBlock = nil; 324 | _cancelBlock = nil; 325 | } 326 | } 327 | 328 | @end 329 | 330 | 331 | @implementation SDWebImageManager (Deprecated) 332 | 333 | // deprecated method, uses the non deprecated method 334 | // adapter for the completion block 335 | - (id )downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock { 336 | return [self downloadImageWithURL:url 337 | options:options 338 | progress:progressBlock 339 | completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 340 | if (completedBlock) { 341 | completedBlock(image, error, cacheType, finished); 342 | } 343 | }]; 344 | } 345 | 346 | @end 347 | -------------------------------------------------------------------------------- /src/ios/SDWebImageOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | 11 | @protocol SDWebImageOperation 12 | 13 | - (void)cancel; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /src/ios/SDWebImagePrefetcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @class SDWebImagePrefetcher; 13 | 14 | @protocol SDWebImagePrefetcherDelegate 15 | 16 | @optional 17 | 18 | /** 19 | * Called when an image was prefetched. 20 | * 21 | * @param imagePrefetcher The current image prefetcher 22 | * @param imageURL The image url that was prefetched 23 | * @param finishedCount The total number of images that were prefetched (successful or not) 24 | * @param totalCount The total number of images that were to be prefetched 25 | */ 26 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount; 27 | 28 | /** 29 | * Called when all images are prefetched. 30 | * @param imagePrefetcher The current image prefetcher 31 | * @param totalCount The total number of images that were prefetched (whether successful or not) 32 | * @param skippedCount The total number of images that were skipped 33 | */ 34 | - (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount; 35 | 36 | @end 37 | 38 | typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls); 39 | typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls); 40 | 41 | /** 42 | * Prefetch some URLs in the cache for future use. Images are downloaded in low priority. 43 | */ 44 | @interface SDWebImagePrefetcher : NSObject 45 | 46 | /** 47 | * The web image manager 48 | */ 49 | @property (strong, nonatomic, readonly) SDWebImageManager *manager; 50 | 51 | /** 52 | * Maximum number of URLs to prefetch at the same time. Defaults to 3. 53 | */ 54 | @property (nonatomic, assign) NSUInteger maxConcurrentDownloads; 55 | 56 | /** 57 | * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. 58 | */ 59 | @property (nonatomic, assign) SDWebImageOptions options; 60 | 61 | @property (weak, nonatomic) id delegate; 62 | 63 | /** 64 | * Return the global image prefetcher instance. 65 | */ 66 | + (SDWebImagePrefetcher *)sharedImagePrefetcher; 67 | 68 | /** 69 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 70 | * currently one image is downloaded at a time, 71 | * and skips images for failed downloads and proceed to the next image in the list 72 | * 73 | * @param urls list of URLs to prefetch 74 | */ 75 | - (void)prefetchURLs:(NSArray *)urls; 76 | 77 | /** 78 | * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, 79 | * currently one image is downloaded at a time, 80 | * and skips images for failed downloads and proceed to the next image in the list 81 | * 82 | * @param urls list of URLs to prefetch 83 | * @param progressBlock block to be called when progress updates; 84 | * first parameter is the number of completed (successful or not) requests, 85 | * second parameter is the total number of images originally requested to be prefetched 86 | * @param completionBlock block to be called when prefetching is completed 87 | * first param is the number of completed (successful or not) requests, 88 | * second parameter is the number of skipped requests 89 | */ 90 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock; 91 | 92 | /** 93 | * Remove and cancel queued list 94 | */ 95 | - (void)cancelPrefetching; 96 | 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /src/ios/SDWebImagePrefetcher.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImagePrefetcher.h" 10 | 11 | #if !defined(DEBUG) && !defined (SD_VERBOSE) 12 | #define NSLog(...) 13 | #endif 14 | 15 | @interface SDWebImagePrefetcher () 16 | 17 | @property (strong, nonatomic) SDWebImageManager *manager; 18 | @property (strong, nonatomic) NSArray *prefetchURLs; 19 | @property (assign, nonatomic) NSUInteger requestedCount; 20 | @property (assign, nonatomic) NSUInteger skippedCount; 21 | @property (assign, nonatomic) NSUInteger finishedCount; 22 | @property (assign, nonatomic) NSTimeInterval startedTime; 23 | @property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock; 24 | @property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock; 25 | 26 | @end 27 | 28 | @implementation SDWebImagePrefetcher 29 | 30 | + (SDWebImagePrefetcher *)sharedImagePrefetcher { 31 | static dispatch_once_t once; 32 | static id instance; 33 | dispatch_once(&once, ^{ 34 | instance = [self new]; 35 | }); 36 | return instance; 37 | } 38 | 39 | - (id)init { 40 | if ((self = [super init])) { 41 | _manager = [SDWebImageManager new]; 42 | _options = SDWebImageLowPriority; 43 | self.maxConcurrentDownloads = 3; 44 | } 45 | return self; 46 | } 47 | 48 | - (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { 49 | self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; 50 | } 51 | 52 | - (NSUInteger)maxConcurrentDownloads { 53 | return self.manager.imageDownloader.maxConcurrentDownloads; 54 | } 55 | 56 | - (void)startPrefetchingAtIndex:(NSUInteger)index { 57 | if (index >= self.prefetchURLs.count) return; 58 | self.requestedCount++; 59 | [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 60 | if (!finished) return; 61 | self.finishedCount++; 62 | 63 | if (image) { 64 | if (self.progressBlock) { 65 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 66 | } 67 | NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count)); 68 | } 69 | else { 70 | if (self.progressBlock) { 71 | self.progressBlock(self.finishedCount,[self.prefetchURLs count]); 72 | } 73 | NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count)); 74 | 75 | // Add last failed 76 | self.skippedCount++; 77 | } 78 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { 79 | [self.delegate imagePrefetcher:self 80 | didPrefetchURL:self.prefetchURLs[index] 81 | finishedCount:self.finishedCount 82 | totalCount:self.prefetchURLs.count 83 | ]; 84 | } 85 | 86 | if (self.prefetchURLs.count > self.requestedCount) { 87 | dispatch_async(dispatch_get_main_queue(), ^{ 88 | [self startPrefetchingAtIndex:self.requestedCount]; 89 | }); 90 | } 91 | else if (self.finishedCount == self.requestedCount) { 92 | [self reportStatus]; 93 | if (self.completionBlock) { 94 | self.completionBlock(self.finishedCount, self.skippedCount); 95 | self.completionBlock = nil; 96 | } 97 | } 98 | }]; 99 | } 100 | 101 | - (void)reportStatus { 102 | NSUInteger total = [self.prefetchURLs count]; 103 | NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime); 104 | if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { 105 | [self.delegate imagePrefetcher:self 106 | didFinishWithTotalCount:(total - self.skippedCount) 107 | skippedCount:self.skippedCount 108 | ]; 109 | } 110 | } 111 | 112 | - (void)prefetchURLs:(NSArray *)urls { 113 | [self prefetchURLs:urls progress:nil completed:nil]; 114 | } 115 | 116 | - (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock { 117 | [self cancelPrefetching]; // Prevent duplicate prefetch request 118 | self.startedTime = CFAbsoluteTimeGetCurrent(); 119 | self.prefetchURLs = urls; 120 | self.completionBlock = completionBlock; 121 | self.progressBlock = progressBlock; 122 | 123 | // Starts prefetching from the very first image on the list with the max allowed concurrency 124 | NSUInteger listCount = self.prefetchURLs.count; 125 | for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { 126 | [self startPrefetchingAtIndex:i]; 127 | } 128 | } 129 | 130 | - (void)cancelPrefetching { 131 | self.prefetchURLs = nil; 132 | self.skippedCount = 0; 133 | self.requestedCount = 0; 134 | self.finishedCount = 0; 135 | [self.manager cancelAll]; 136 | } 137 | 138 | @end 139 | -------------------------------------------------------------------------------- /src/ios/UIImage+GIF.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.h 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (GIF) 12 | 13 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name; 14 | 15 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data; 16 | 17 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /src/ios/UIImage+GIF.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+GIF.m 3 | // LBGIFImage 4 | // 5 | // Created by Laurin Brandner on 06.01.12. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import "UIImage+GIF.h" 10 | #import 11 | 12 | @implementation UIImage (GIF) 13 | 14 | + (UIImage *)sd_animatedGIFWithData:(NSData *)data { 15 | if (!data) { 16 | return nil; 17 | } 18 | 19 | CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); 20 | 21 | size_t count = CGImageSourceGetCount(source); 22 | 23 | UIImage *animatedImage; 24 | 25 | if (count <= 1) { 26 | animatedImage = [[UIImage alloc] initWithData:data]; 27 | } 28 | else { 29 | NSMutableArray *images = [NSMutableArray array]; 30 | 31 | NSTimeInterval duration = 0.0f; 32 | 33 | for (size_t i = 0; i < count; i++) { 34 | CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL); 35 | 36 | duration += [self sd_frameDurationAtIndex:i source:source]; 37 | 38 | [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]]; 39 | 40 | CGImageRelease(image); 41 | } 42 | 43 | if (!duration) { 44 | duration = (1.0f / 10.0f) * count; 45 | } 46 | 47 | animatedImage = [UIImage animatedImageWithImages:images duration:duration]; 48 | } 49 | 50 | CFRelease(source); 51 | 52 | return animatedImage; 53 | } 54 | 55 | + (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { 56 | float frameDuration = 0.1f; 57 | CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); 58 | NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; 59 | NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; 60 | 61 | NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; 62 | if (delayTimeUnclampedProp) { 63 | frameDuration = [delayTimeUnclampedProp floatValue]; 64 | } 65 | else { 66 | 67 | NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; 68 | if (delayTimeProp) { 69 | frameDuration = [delayTimeProp floatValue]; 70 | } 71 | } 72 | 73 | // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. 74 | // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify 75 | // a duration of <= 10 ms. See and 76 | // for more information. 77 | 78 | if (frameDuration < 0.011f) { 79 | frameDuration = 0.100f; 80 | } 81 | 82 | CFRelease(cfFrameProperties); 83 | return frameDuration; 84 | } 85 | 86 | + (UIImage *)sd_animatedGIFNamed:(NSString *)name { 87 | CGFloat scale = [UIScreen mainScreen].scale; 88 | 89 | if (scale > 1.0f) { 90 | NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"]; 91 | 92 | NSData *data = [NSData dataWithContentsOfFile:retinaPath]; 93 | 94 | if (data) { 95 | return [UIImage sd_animatedGIFWithData:data]; 96 | } 97 | 98 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 99 | 100 | data = [NSData dataWithContentsOfFile:path]; 101 | 102 | if (data) { 103 | return [UIImage sd_animatedGIFWithData:data]; 104 | } 105 | 106 | return [UIImage imageNamed:name]; 107 | } 108 | else { 109 | NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"]; 110 | 111 | NSData *data = [NSData dataWithContentsOfFile:path]; 112 | 113 | if (data) { 114 | return [UIImage sd_animatedGIFWithData:data]; 115 | } 116 | 117 | return [UIImage imageNamed:name]; 118 | } 119 | } 120 | 121 | - (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size { 122 | if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) { 123 | return self; 124 | } 125 | 126 | CGSize scaledSize = size; 127 | CGPoint thumbnailPoint = CGPointZero; 128 | 129 | CGFloat widthFactor = size.width / self.size.width; 130 | CGFloat heightFactor = size.height / self.size.height; 131 | CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor; 132 | scaledSize.width = self.size.width * scaleFactor; 133 | scaledSize.height = self.size.height * scaleFactor; 134 | 135 | if (widthFactor > heightFactor) { 136 | thumbnailPoint.y = (size.height - scaledSize.height) * 0.5; 137 | } 138 | else if (widthFactor < heightFactor) { 139 | thumbnailPoint.x = (size.width - scaledSize.width) * 0.5; 140 | } 141 | 142 | NSMutableArray *scaledImages = [NSMutableArray array]; 143 | 144 | UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 145 | 146 | for (UIImage *image in self.images) { 147 | [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)]; 148 | UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 149 | 150 | [scaledImages addObject:newImage]; 151 | } 152 | 153 | UIGraphicsEndImageContext(); 154 | 155 | return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; 156 | } 157 | 158 | @end 159 | -------------------------------------------------------------------------------- /src/ios/UIImage+MultiFormat.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface UIImage (MultiFormat) 12 | 13 | + (UIImage *)sd_imageWithData:(NSData *)data; 14 | 15 | @end 16 | -------------------------------------------------------------------------------- /src/ios/UIImage+MultiFormat.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+MultiFormat.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #import "UIImage+MultiFormat.h" 10 | #import "UIImage+GIF.h" 11 | #import "NSData+ImageContentType.h" 12 | #import 13 | 14 | #ifdef SD_WEBP 15 | #import "UIImage+WebP.h" 16 | #endif 17 | 18 | @implementation UIImage (MultiFormat) 19 | 20 | + (UIImage *)sd_imageWithData:(NSData *)data { 21 | UIImage *image; 22 | NSString *imageContentType = [NSData sd_contentTypeForImageData:data]; 23 | if ([imageContentType isEqualToString:@"image/gif"]) { 24 | image = [UIImage sd_animatedGIFWithData:data]; 25 | } 26 | #ifdef SD_WEBP 27 | else if ([imageContentType isEqualToString:@"image/webp"]) 28 | { 29 | image = [UIImage sd_imageWithWebPData:data]; 30 | } 31 | #endif 32 | else { 33 | image = [[UIImage alloc] initWithData:data]; 34 | UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data]; 35 | if (orientation != UIImageOrientationUp) { 36 | image = [UIImage imageWithCGImage:image.CGImage 37 | scale:image.scale 38 | orientation:orientation]; 39 | } 40 | } 41 | 42 | 43 | return image; 44 | } 45 | 46 | 47 | +(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData { 48 | UIImageOrientation result = UIImageOrientationUp; 49 | CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL); 50 | if (imageSource) { 51 | CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL); 52 | if (properties) { 53 | CFTypeRef val; 54 | int exifOrientation; 55 | val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation); 56 | if (val) { 57 | CFNumberGetValue(val, kCFNumberIntType, &exifOrientation); 58 | result = [self sd_exifOrientationToiOSOrientation:exifOrientation]; 59 | } // else - if it's not set it remains at up 60 | CFRelease((CFTypeRef) properties); 61 | } else { 62 | //NSLog(@"NO PROPERTIES, FAIL"); 63 | } 64 | CFRelease(imageSource); 65 | } 66 | return result; 67 | } 68 | 69 | #pragma mark EXIF orientation tag converter 70 | // Convert an EXIF image orientation to an iOS one. 71 | // reference see here: http://sylvana.net/jpegcrop/exif_orientation.html 72 | + (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation { 73 | UIImageOrientation orientation = UIImageOrientationUp; 74 | switch (exifOrientation) { 75 | case 1: 76 | orientation = UIImageOrientationUp; 77 | break; 78 | 79 | case 3: 80 | orientation = UIImageOrientationDown; 81 | break; 82 | 83 | case 8: 84 | orientation = UIImageOrientationLeft; 85 | break; 86 | 87 | case 6: 88 | orientation = UIImageOrientationRight; 89 | break; 90 | 91 | case 2: 92 | orientation = UIImageOrientationUpMirrored; 93 | break; 94 | 95 | case 4: 96 | orientation = UIImageOrientationDownMirrored; 97 | break; 98 | 99 | case 5: 100 | orientation = UIImageOrientationLeftMirrored; 101 | break; 102 | 103 | case 7: 104 | orientation = UIImageOrientationRightMirrored; 105 | break; 106 | default: 107 | break; 108 | } 109 | return orientation; 110 | } 111 | 112 | 113 | 114 | @end 115 | -------------------------------------------------------------------------------- /src/ios/UIImage+ResizeMagick.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+ResizeMagick.h 3 | // 4 | // 5 | // Created by Vlad Andersen on 1/5/13. 6 | // 7 | // 8 | 9 | 10 | 11 | @interface UIImage (ResizeMagick) 12 | 13 | - (UIImage *) resizedImageByMagick: (NSString *) spec; 14 | - (UIImage *) resizedImageByWidth: (NSUInteger) width; 15 | - (UIImage *) resizedImageByHeight: (NSUInteger) height; 16 | - (UIImage *) resizedImageWithMaximumSize: (CGSize) size; 17 | - (UIImage *) resizedImageWithMinimumSize: (CGSize) size; 18 | 19 | @end 20 | -------------------------------------------------------------------------------- /src/ios/UIImage+ResizeMagick.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+ResizeMagick.m 3 | // 4 | // 5 | // Created by Vlad Andersen on 1/5/13. 6 | // 7 | // 8 | 9 | #import "UIImage+ResizeMagick.h" 10 | 11 | @implementation UIImage (ResizeMagick) 12 | 13 | // width Width given, height automagically selected to preserve aspect ratio. 14 | // xheight Height given, width automagically selected to preserve aspect ratio. 15 | // widthxheight Maximum values of height and width given, aspect ratio preserved. 16 | // widthxheight^ Minimum values of width and height given, aspect ratio preserved. 17 | // widthxheight! Exact dimensions, no aspect ratio preserved. 18 | // widthxheight# Crop to this exact dimensions. 19 | 20 | - (UIImage *) resizedImageByMagick: (NSString *) spec 21 | { 22 | 23 | if([spec hasSuffix:@"!"]) { 24 | NSString *specWithoutSuffix = [spec substringToIndex: [spec length] - 1]; 25 | NSArray *widthAndHeight = [specWithoutSuffix componentsSeparatedByString: @"x"]; 26 | NSUInteger width = (unsigned int)[[widthAndHeight objectAtIndex: 0] longLongValue]; 27 | NSUInteger height = (unsigned int)[[widthAndHeight objectAtIndex: 1] longLongValue]; 28 | UIImage *newImage = [self resizedImageWithMinimumSize: CGSizeMake (width, height)]; 29 | return [newImage drawImageInBounds: CGRectMake (0, 0, width, height)]; 30 | } 31 | 32 | if([spec hasSuffix:@"#"]) { 33 | NSString *specWithoutSuffix = [spec substringToIndex: [spec length] - 1]; 34 | NSArray *widthAndHeight = [specWithoutSuffix componentsSeparatedByString: @"x"]; 35 | NSUInteger width = (unsigned int)[[widthAndHeight objectAtIndex: 0] longLongValue]; 36 | NSUInteger height = (unsigned int)[[widthAndHeight objectAtIndex: 1] longLongValue]; 37 | UIImage *newImage = [self resizedImageWithMinimumSize: CGSizeMake (width, height)]; 38 | return [newImage croppedImageWithRect: CGRectMake ((newImage.size.width - width) / 2, (newImage.size.height - height) / 2, width, height)]; 39 | } 40 | 41 | if([spec hasSuffix:@"^"]) { 42 | NSString *specWithoutSuffix = [spec substringToIndex: [spec length] - 1]; 43 | NSArray *widthAndHeight = [specWithoutSuffix componentsSeparatedByString: @"x"]; 44 | return [self resizedImageWithMinimumSize: CGSizeMake ([[widthAndHeight objectAtIndex: 0] longLongValue], 45 | [[widthAndHeight objectAtIndex: 1] longLongValue])]; 46 | } 47 | 48 | NSArray *widthAndHeight = [spec componentsSeparatedByString: @"x"]; 49 | if ([widthAndHeight count] == 1) { 50 | return [self resizedImageByWidth:(unsigned int)[spec longLongValue]]; 51 | } 52 | if ([[widthAndHeight objectAtIndex: 0] isEqualToString: @""]) { 53 | return [self resizedImageByHeight:(unsigned int)[[widthAndHeight objectAtIndex: 1] longLongValue]]; 54 | } 55 | return [self resizedImageWithMaximumSize: CGSizeMake ([[widthAndHeight objectAtIndex: 0] longLongValue], 56 | [[widthAndHeight objectAtIndex: 1] longLongValue])]; 57 | } 58 | 59 | - (CGImageRef) CGImageWithCorrectOrientation 60 | { 61 | if (self.imageOrientation == UIImageOrientationDown) { 62 | //retaining because caller expects to own the reference 63 | CGImageRetain([self CGImage]); 64 | return [self CGImage]; 65 | } 66 | UIGraphicsBeginImageContext(self.size); 67 | 68 | CGContextRef context = UIGraphicsGetCurrentContext(); 69 | 70 | if (self.imageOrientation == UIImageOrientationRight) { 71 | CGContextRotateCTM (context, 90 * M_PI/180); 72 | } else if (self.imageOrientation == UIImageOrientationLeft) { 73 | CGContextRotateCTM (context, -90 * M_PI/180); 74 | } else if (self.imageOrientation == UIImageOrientationUp) { 75 | CGContextRotateCTM (context, 180 * M_PI/180); 76 | } 77 | 78 | [self drawAtPoint:CGPointMake(0, 0)]; 79 | 80 | CGImageRef cgImage = CGBitmapContextCreateImage(context); 81 | UIGraphicsEndImageContext(); 82 | 83 | return cgImage; 84 | } 85 | 86 | 87 | - (UIImage *) resizedImageByWidth: (NSUInteger) width 88 | { 89 | CGImageRef imgRef = [self CGImageWithCorrectOrientation]; 90 | CGFloat original_width = CGImageGetWidth(imgRef); 91 | CGFloat original_height = CGImageGetHeight(imgRef); 92 | CGFloat ratio = width/original_width; 93 | CGImageRelease(imgRef); 94 | return [self drawImageInBounds: CGRectMake(0, 0, width, round(original_height * ratio))]; 95 | } 96 | 97 | - (UIImage *) resizedImageByHeight: (NSUInteger) height 98 | { 99 | CGImageRef imgRef = [self CGImageWithCorrectOrientation]; 100 | CGFloat original_width = CGImageGetWidth(imgRef); 101 | CGFloat original_height = CGImageGetHeight(imgRef); 102 | CGFloat ratio = height/original_height; 103 | CGImageRelease(imgRef); 104 | return [self drawImageInBounds: CGRectMake(0, 0, round(original_width * ratio), height)]; 105 | } 106 | 107 | - (UIImage *) resizedImageWithMinimumSize: (CGSize) size 108 | { 109 | CGImageRef imgRef = [self CGImageWithCorrectOrientation]; 110 | CGFloat original_width = CGImageGetWidth(imgRef); 111 | CGFloat original_height = CGImageGetHeight(imgRef); 112 | CGFloat width_ratio = size.width / original_width; 113 | CGFloat height_ratio = size.height / original_height; 114 | CGFloat scale_ratio = width_ratio > height_ratio ? width_ratio : height_ratio; 115 | CGImageRelease(imgRef); 116 | return [self drawImageInBounds: CGRectMake(0, 0, round(original_width * scale_ratio), round(original_height * scale_ratio))]; 117 | } 118 | 119 | - (UIImage *) resizedImageWithMaximumSize: (CGSize) size 120 | { 121 | CGImageRef imgRef = [self CGImageWithCorrectOrientation]; 122 | CGFloat original_width = CGImageGetWidth(imgRef); 123 | CGFloat original_height = CGImageGetHeight(imgRef); 124 | CGFloat width_ratio = size.width / original_width; 125 | CGFloat height_ratio = size.height / original_height; 126 | CGFloat scale_ratio = width_ratio < height_ratio ? width_ratio : height_ratio; 127 | CGImageRelease(imgRef); 128 | return [self drawImageInBounds: CGRectMake(0, 0, round(original_width * scale_ratio), round(original_height * scale_ratio))]; 129 | } 130 | 131 | - (UIImage *) drawImageInBounds: (CGRect) bounds 132 | { 133 | UIGraphicsBeginImageContext(bounds.size); 134 | [self drawInRect: bounds]; 135 | UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext(); 136 | UIGraphicsEndImageContext(); 137 | return resizedImage; 138 | } 139 | 140 | - (UIImage*) croppedImageWithRect: (CGRect) rect { 141 | 142 | UIGraphicsBeginImageContext(rect.size); 143 | CGContextRef context = UIGraphicsGetCurrentContext(); 144 | CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, self.size.width, self.size.height); 145 | CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height)); 146 | [self drawInRect:drawRect]; 147 | UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext(); 148 | UIGraphicsEndImageContext(); 149 | 150 | return subImage; 151 | } 152 | 153 | 154 | @end 155 | -------------------------------------------------------------------------------- /src/ios/UIImage+WebP.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.h 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | 11 | #import 12 | 13 | // Fix for issue #416 Undefined symbols for architecture armv7 since WebP introduction when deploying to device 14 | void WebPInitPremultiplyNEON(void); 15 | 16 | void WebPInitUpsamplersNEON(void); 17 | 18 | void VP8DspInitNEON(void); 19 | 20 | @interface UIImage (WebP) 21 | 22 | + (UIImage *)sd_imageWithWebPData:(NSData *)data; 23 | 24 | @end 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /src/ios/UIImage+WebP.m: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+WebP.m 3 | // SDWebImage 4 | // 5 | // Created by Olivier Poitrey on 07/06/13. 6 | // Copyright (c) 2013 Dailymotion. All rights reserved. 7 | // 8 | 9 | #ifdef SD_WEBP 10 | #import "UIImage+WebP.h" 11 | #import "webp/decode.h" 12 | 13 | // Callback for CGDataProviderRelease 14 | static void FreeImageData(void *info, const void *data, size_t size) 15 | { 16 | free((void *)data); 17 | } 18 | 19 | @implementation UIImage (WebP) 20 | 21 | + (UIImage *)sd_imageWithWebPData:(NSData *)data { 22 | WebPDecoderConfig config; 23 | if (!WebPInitDecoderConfig(&config)) { 24 | return nil; 25 | } 26 | 27 | config.output.colorspace = MODE_rgbA; 28 | config.options.use_threads = 1; 29 | 30 | // Decode the WebP image data into a RGBA value array. 31 | if (WebPDecode(data.bytes, data.length, &config) != VP8_STATUS_OK) { 32 | return nil; 33 | } 34 | 35 | int width = config.input.width; 36 | int height = config.input.height; 37 | if (config.options.use_scaling) { 38 | width = config.options.scaled_width; 39 | height = config.options.scaled_height; 40 | } 41 | 42 | // Construct a UIImage from the decoded RGBA value array. 43 | CGDataProviderRef provider = 44 | CGDataProviderCreateWithData(NULL, config.output.u.RGBA.rgba, config.output.u.RGBA.size, FreeImageData); 45 | CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); 46 | CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast; 47 | CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; 48 | CGImageRef imageRef = CGImageCreate(width, height, 8, 32, 4 * width, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); 49 | 50 | CGColorSpaceRelease(colorSpaceRef); 51 | CGDataProviderRelease(provider); 52 | 53 | UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; 54 | CGImageRelease(imageRef); 55 | 56 | return image; 57 | } 58 | 59 | @end 60 | 61 | #if !COCOAPODS 62 | // Functions to resolve some undefined symbols when using WebP and force_load flag 63 | void WebPInitPremultiplyNEON(void) {} 64 | void WebPInitUpsamplersNEON(void) {} 65 | void VP8DspInitNEON(void) {} 66 | #endif 67 | 68 | #endif 69 | -------------------------------------------------------------------------------- /src/ios/UIImageView+WebCache.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "SDWebImageCompat.h" 10 | #import "SDWebImageManager.h" 11 | 12 | /** 13 | * Integrates SDWebImage async downloading and caching of remote images with UIImageView. 14 | * 15 | * Usage with a UITableViewCell sub-class: 16 | * 17 | * @code 18 | 19 | #import 20 | 21 | ... 22 | 23 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 24 | { 25 | static NSString *MyIdentifier = @"MyIdentifier"; 26 | 27 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 28 | 29 | if (cell == nil) { 30 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] 31 | autorelease]; 32 | } 33 | 34 | // Here we use the provided sd_setImageWithURL: method to load the web image 35 | // Ensure you use a placeholder image otherwise cells will be initialized with no image 36 | [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 37 | placeholderImage:[UIImage imageNamed:@"placeholder"]]; 38 | 39 | cell.textLabel.text = @"My Text"; 40 | return cell; 41 | } 42 | 43 | * @endcode 44 | */ 45 | @interface UIImageView (WebCache) 46 | 47 | /** 48 | * Get the current image URL. 49 | * 50 | * Note that because of the limitations of categories this property can get out of sync 51 | * if you use sd_setImage: directly. 52 | */ 53 | - (NSURL *)sd_imageURL; 54 | 55 | /** 56 | * Set the imageView `image` with an `url`. 57 | * 58 | * The download is asynchronous and cached. 59 | * 60 | * @param url The url for the image. 61 | */ 62 | - (void)sd_setImageWithURL:(NSURL *)url; 63 | 64 | /** 65 | * Set the imageView `image` with an `url` and a placeholder. 66 | * 67 | * The download is asynchronous and cached. 68 | * 69 | * @param url The url for the image. 70 | * @param placeholder The image to be set initially, until the image request finishes. 71 | * @see sd_setImageWithURL:placeholderImage:options: 72 | */ 73 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; 74 | 75 | /** 76 | * Set the imageView `image` with an `url`, placeholder and custom options. 77 | * 78 | * The download is asynchronous and cached. 79 | * 80 | * @param url The url for the image. 81 | * @param placeholder The image to be set initially, until the image request finishes. 82 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 83 | */ 84 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options; 85 | 86 | /** 87 | * Set the imageView `image` with an `url`. 88 | * 89 | * The download is asynchronous and cached. 90 | * 91 | * @param url The url for the image. 92 | * @param completedBlock A block called when operation has been completed. This block has no return value 93 | * and takes the requested UIImage as first parameter. In case of error the image parameter 94 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 95 | * indicating if the image was retrived from the local cache of from the network. 96 | * The forth parameter is the original image url. 97 | */ 98 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock; 99 | 100 | /** 101 | * Set the imageView `image` with an `url`, placeholder. 102 | * 103 | * The download is asynchronous and cached. 104 | * 105 | * @param url The url for the image. 106 | * @param placeholder The image to be set initially, until the image request finishes. 107 | * @param completedBlock A block called when operation has been completed. This block has no return value 108 | * and takes the requested UIImage as first parameter. In case of error the image parameter 109 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 110 | * indicating if the image was retrived from the local cache of from the network. 111 | * The forth parameter is the original image url. 112 | */ 113 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock; 114 | 115 | /** 116 | * Set the imageView `image` with an `url`, placeholder and custom options. 117 | * 118 | * The download is asynchronous and cached. 119 | * 120 | * @param url The url for the image. 121 | * @param placeholder The image to be set initially, until the image request finishes. 122 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 123 | * @param completedBlock A block called when operation has been completed. This block has no return value 124 | * and takes the requested UIImage as first parameter. In case of error the image parameter 125 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 126 | * indicating if the image was retrived from the local cache of from the network. 127 | * The forth parameter is the original image url. 128 | */ 129 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock; 130 | 131 | /** 132 | * Set the imageView `image` with an `url`, placeholder and custom options. 133 | * 134 | * The download is asynchronous and cached. 135 | * 136 | * @param url The url for the image. 137 | * @param placeholder The image to be set initially, until the image request finishes. 138 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 139 | * @param progressBlock A block called while image is downloading 140 | * @param completedBlock A block called when operation has been completed. This block has no return value 141 | * and takes the requested UIImage as first parameter. In case of error the image parameter 142 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 143 | * indicating if the image was retrived from the local cache of from the network. 144 | * The forth parameter is the original image url. 145 | */ 146 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 147 | 148 | /** 149 | * Set the imageView `image` with an `url` and a optionaly placeholder image. 150 | * 151 | * The download is asynchronous and cached. 152 | * 153 | * @param url The url for the image. 154 | * @param placeholder The image to be set initially, until the image request finishes. 155 | * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values. 156 | * @param progressBlock A block called while image is downloading 157 | * @param completedBlock A block called when operation has been completed. This block has no return value 158 | * and takes the requested UIImage as first parameter. In case of error the image parameter 159 | * is nil and the second parameter may contain an NSError. The third parameter is a Boolean 160 | * indicating if the image was retrived from the local cache of from the network. 161 | * The forth parameter is the original image url. 162 | */ 163 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock; 164 | 165 | /** 166 | * Download an array of images and starts them in an animation loop 167 | * 168 | * @param arrayOfURLs An array of NSURL 169 | */ 170 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs; 171 | 172 | /** 173 | * Cancel the current download 174 | */ 175 | - (void)sd_cancelCurrentImageLoad; 176 | 177 | - (void)sd_cancelCurrentAnimationImagesLoad; 178 | 179 | @end 180 | 181 | 182 | @interface UIImageView (WebCacheDeprecated) 183 | 184 | - (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`"); 185 | 186 | - (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`"); 187 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`"); 188 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`"); 189 | 190 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`"); 191 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`"); 192 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`"); 193 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:progress:completed:`"); 194 | 195 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`"); 196 | 197 | - (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`"); 198 | 199 | - (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`"); 200 | 201 | @end 202 | -------------------------------------------------------------------------------- /src/ios/UIImageView+WebCache.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIImageView+WebCache.h" 10 | #import "objc/runtime.h" 11 | #import "UIView+WebCacheOperation.h" 12 | 13 | static char imageURLKey; 14 | 15 | @implementation UIImageView (WebCache) 16 | 17 | - (void)sd_setImageWithURL:(NSURL *)url { 18 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 19 | } 20 | 21 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 22 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 23 | } 24 | 25 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 26 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 27 | } 28 | 29 | - (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock { 30 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock]; 31 | } 32 | 33 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock { 34 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock]; 35 | } 36 | 37 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock { 38 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock]; 39 | } 40 | 41 | - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 42 | [self sd_cancelCurrentImageLoad]; 43 | objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 44 | 45 | if (!(options & SDWebImageDelayPlaceholder)) { 46 | self.image = placeholder; 47 | } 48 | 49 | if (url) { 50 | __weak UIImageView *wself = self; 51 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 52 | if (!wself) return; 53 | dispatch_main_sync_safe(^{ 54 | if (!wself) return; 55 | if (image) { 56 | wself.image = image; 57 | [wself setNeedsLayout]; 58 | } else { 59 | if ((options & SDWebImageDelayPlaceholder)) { 60 | wself.image = placeholder; 61 | [wself setNeedsLayout]; 62 | } 63 | } 64 | if (completedBlock && finished) { 65 | completedBlock(image, error, cacheType, url); 66 | } 67 | }); 68 | }]; 69 | [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 70 | } else { 71 | dispatch_main_async_safe(^{ 72 | NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 73 | if (completedBlock) { 74 | completedBlock(nil, error, SDImageCacheTypeNone, url); 75 | } 76 | }); 77 | } 78 | } 79 | 80 | - (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 81 | NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; 82 | UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key]; 83 | 84 | [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; 85 | } 86 | 87 | - (NSURL *)sd_imageURL { 88 | return objc_getAssociatedObject(self, &imageURLKey); 89 | } 90 | 91 | - (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 92 | [self sd_cancelCurrentAnimationImagesLoad]; 93 | __weak UIImageView *wself = self; 94 | 95 | NSMutableArray *operationsArray = [[NSMutableArray alloc] init]; 96 | 97 | for (NSURL *logoImageURL in arrayOfURLs) { 98 | id operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 99 | if (!wself) return; 100 | dispatch_main_sync_safe(^{ 101 | __strong UIImageView *sself = wself; 102 | [sself stopAnimating]; 103 | if (sself && image) { 104 | NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; 105 | if (!currentImages) { 106 | currentImages = [[NSMutableArray alloc] init]; 107 | } 108 | [currentImages addObject:image]; 109 | 110 | sself.animationImages = currentImages; 111 | [sself setNeedsLayout]; 112 | } 113 | [sself startAnimating]; 114 | }); 115 | }]; 116 | [operationsArray addObject:operation]; 117 | } 118 | 119 | [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"]; 120 | } 121 | 122 | - (void)sd_cancelCurrentImageLoad { 123 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"]; 124 | } 125 | 126 | - (void)sd_cancelCurrentAnimationImagesLoad { 127 | [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"]; 128 | } 129 | 130 | @end 131 | 132 | 133 | @implementation UIImageView (WebCacheDeprecated) 134 | 135 | - (NSURL *)imageURL { 136 | return [self sd_imageURL]; 137 | } 138 | 139 | - (void)setImageWithURL:(NSURL *)url { 140 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil]; 141 | } 142 | 143 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder { 144 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil]; 145 | } 146 | 147 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options { 148 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil]; 149 | } 150 | 151 | - (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock { 152 | [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 153 | if (completedBlock) { 154 | completedBlock(image, error, cacheType); 155 | } 156 | }]; 157 | } 158 | 159 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock { 160 | [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 161 | if (completedBlock) { 162 | completedBlock(image, error, cacheType); 163 | } 164 | }]; 165 | } 166 | 167 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock { 168 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 169 | if (completedBlock) { 170 | completedBlock(image, error, cacheType); 171 | } 172 | }]; 173 | } 174 | 175 | - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock { 176 | [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 177 | if (completedBlock) { 178 | completedBlock(image, error, cacheType); 179 | } 180 | }]; 181 | } 182 | 183 | - (void)cancelCurrentArrayLoad { 184 | [self sd_cancelCurrentAnimationImagesLoad]; 185 | } 186 | 187 | - (void)cancelCurrentImageLoad { 188 | [self sd_cancelCurrentImageLoad]; 189 | } 190 | 191 | - (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs { 192 | [self sd_setAnimationImagesWithURLs:arrayOfURLs]; 193 | } 194 | 195 | @end 196 | -------------------------------------------------------------------------------- /src/ios/UIView+WebCacheOperation.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import 10 | #import "SDWebImageManager.h" 11 | 12 | @interface UIView (WebCacheOperation) 13 | 14 | /** 15 | * Set the image load operation (storage in a UIView based dictionary) 16 | * 17 | * @param operation the operation 18 | * @param key key for storing the operation 19 | */ 20 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key; 21 | 22 | /** 23 | * Cancel all operations for the current UIView and key 24 | * 25 | * @param key key for identifying the operations 26 | */ 27 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key; 28 | 29 | /** 30 | * Just remove the operations corresponding to the current UIView and key without cancelling them 31 | * 32 | * @param key key for identifying the operations 33 | */ 34 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key; 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /src/ios/UIView+WebCacheOperation.m: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the SDWebImage package. 3 | * (c) Olivier Poitrey 4 | * 5 | * For the full copyright and license information, please view the LICENSE 6 | * file that was distributed with this source code. 7 | */ 8 | 9 | #import "UIView+WebCacheOperation.h" 10 | #import "objc/runtime.h" 11 | 12 | static char loadOperationKey; 13 | 14 | @implementation UIView (WebCacheOperation) 15 | 16 | - (NSMutableDictionary *)operationDictionary { 17 | NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey); 18 | if (operations) { 19 | return operations; 20 | } 21 | operations = [NSMutableDictionary dictionary]; 22 | objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 23 | return operations; 24 | } 25 | 26 | - (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key { 27 | [self sd_cancelImageLoadOperationWithKey:key]; 28 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 29 | [operationDictionary setObject:operation forKey:key]; 30 | } 31 | 32 | - (void)sd_cancelImageLoadOperationWithKey:(NSString *)key { 33 | // Cancel in progress downloader from queue 34 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 35 | id operations = [operationDictionary objectForKey:key]; 36 | if (operations) { 37 | if ([operations isKindOfClass:[NSArray class]]) { 38 | for (id operation in operations) { 39 | if (operation) { 40 | [operation cancel]; 41 | } 42 | } 43 | } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){ 44 | [(id) operations cancel]; 45 | } 46 | [operationDictionary removeObjectForKey:key]; 47 | } 48 | } 49 | 50 | - (void)sd_removeImageLoadOperationWithKey:(NSString *)key { 51 | NSMutableDictionary *operationDictionary = [self operationDictionary]; 52 | [operationDictionary removeObjectForKey:key]; 53 | } 54 | 55 | @end 56 | -------------------------------------------------------------------------------- /www/CollectionRepeatImage.js: -------------------------------------------------------------------------------- 1 | var exec = require('cordova/exec'); 2 | 3 | var CollectionRepeatImage = function () { 4 | 5 | }; 6 | 7 | CollectionRepeatImage.getImage = function(options, success, error) { 8 | exec(success, error, "CollectionRepeatImage", "getImage", [options]); 9 | }; 10 | 11 | CollectionRepeatImage.cancel = function(index, success, error) { 12 | exec(success, error, "CollectionRepeatImage", "cancel", [index]); 13 | }; 14 | 15 | CollectionRepeatImage.cancelAll = function(args, success, error) { 16 | exec(null, null, "CollectionRepeatImage", "cancelAll", []); 17 | }; 18 | 19 | module.exports = CollectionRepeatImage; -------------------------------------------------------------------------------- /www/CollectionRepeatImageOptions.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = { 3 | /** 4 | * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 5 | * This flag disable this blacklisting. 6 | */ 7 | SDWebImageRetryFailed: 1 << 0, 8 | 9 | /** 10 | * By default, image downloads are started during UI interactions, this flags disable this feature, 11 | * leading to delayed download on UIScrollView deceleration for instance. 12 | */ 13 | SDWebImageLowPriority: 1 << 1, 14 | 15 | /** 16 | * This flag disables on-disk caching 17 | */ 18 | SDWebImageCacheMemoryOnly: 1 << 2, 19 | 20 | /** 21 | * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 22 | * By default, the image is only displayed once completely downloaded. 23 | */ 24 | SDWebImageProgressiveDownload: 1 << 3, 25 | 26 | /** 27 | * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 28 | * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 29 | * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 30 | * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 31 | * 32 | * Use this flag only if you can't make your URLs static with embeded cache busting parameter. 33 | */ 34 | SDWebImageRefreshCached: 1 << 4, 35 | 36 | /** 37 | * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 38 | * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 39 | */ 40 | SDWebImageContinueInBackground: 1 << 5, 41 | 42 | /** 43 | * Handles cookies stored in NSHTTPCookieStore by setting 44 | * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 45 | */ 46 | SDWebImageHandleCookies: 1 << 6, 47 | 48 | /** 49 | * Enable to allow untrusted SSL ceriticates. 50 | * Useful for testing purposes. Use with caution in production. 51 | */ 52 | SDWebImageAllowInvalidSSLCertificates: 1 << 7, 53 | 54 | /** 55 | * By default, image are loaded in the order they were queued. This flag move them to 56 | * the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which 57 | * could take a while). 58 | */ 59 | SDWebImageHighPriority: 1 << 8, 60 | 61 | /** 62 | * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 63 | * of the placeholder image until after the image has finished loading. 64 | */ 65 | SDWebImageDelayPlaceholder: 1 << 9 66 | } --------------------------------------------------------------------------------