Project import
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..ae783e1
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2009 Olivier Poitrey <rs@dailymotion.com>
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+ 
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+ 
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9bbcca5
--- /dev/null
+++ b/README.md
@@ -0,0 +1,280 @@
+Web Image
+=========
+[![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage)
+[![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
+[![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
+[![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html)
+
+This library provides a category for UIImageView with support for remote images coming from the web.
+
+It provides:
+
+- An UIImageView category adding web image and cache management to the Cocoa Touch framework
+- An asynchronous image downloader
+- An asynchronous memory + disk image caching with automatic cache expiration handling
+- Animated GIF support
+- WebP format support
+- A background image decompression
+- A guarantee that the same URL won't be downloaded several times
+- A guarantee that bogus URLs won't be retried again and again
+- A guarantee that main thread will never be blocked
+- Performances!
+- Use GCD and ARC
+- Arm64 support
+
+NOTE: The version 3.0 of SDWebImage isn't fully backward compatible with 2.0 and requires iOS 5.1.1
+minimum deployement version. If you need iOS < 5.0 support, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat).
+
+[How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F)
+
+Who Use It
+----------
+
+Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list.
+
+How To Use
+----------
+
+API documentation is available at [http://hackemist.com/SDWebImage/doc/](http://hackemist.com/SDWebImage/doc/)
+
+### Using UIImageView+WebCache category with UITableView
+
+Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage:
+method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be
+handled for you, from async downloads to caching management.
+
+```objective-c
+#import <SDWebImage/UIImageView+WebCache.h>
+
+...
+
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
+{
+    static NSString *MyIdentifier = @"MyIdentifier";
+
+    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
+
+    if (cell == nil)
+    {
+        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
+                                       reuseIdentifier:MyIdentifier] autorelease];
+    }
+
+    // Here we use the new provided setImageWithURL: method to load the web image
+    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
+                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
+
+    cell.textLabel.text = @"My Text";
+    return cell;
+}
+```
+
+### Using blocks
+
+With blocks, you can be notified about the image download progress and whenever the image retrival
+has completed with success or not:
+
+```objective-c
+// Here we use the new provided setImageWithURL: method to load the web image
+[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
+               placeholderImage:[UIImage imageNamed:@"placeholder.png"]
+                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];
+```
+
+Note: neither your success nor failure block will be call if your image request is canceled before completion.
+
+### Using SDWebImageManager
+
+The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the
+asynchronous downloader with the image cache store. You can use this class directly to benefit
+from web image downloading with caching in another context than a UIView (ie: with Cocoa).
+
+Here is a simple example of how to use SDWebImageManager:
+
+```objective-c
+SDWebImageManager *manager = [SDWebImageManager sharedManager];
+[manager downloadWithURL:imageURL
+                 options:0
+                 progress:^(NSInteger receivedSize, NSInteger expectedSize)
+                 {
+                     // progression tracking code
+                 }
+                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
+                 {
+                     if (image)
+                     {
+                         // do something with image
+                     }
+                 }];
+```
+
+### Using Asynchronous Image Downloader Independently
+
+It's also possible to use the async image downloader independently:
+
+```objective-c
+[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
+                                                    options:0
+                                                   progress:^(NSInteger receivedSize, NSInteger expectedSize)
+                                                   {
+                                                       // progression tracking code
+                                                   }
+                                                   completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
+                                                   {
+                                                       if (image && finished)
+                                                       {
+                                                           // do something with image
+                                                       }
+                                                   }];
+```
+
+### Using Asynchronous Image Caching Independently
+
+It is also possible to use the aync based image cache store independently. SDImageCache
+maintains a memory cache and an optional disk cache. Disk cache write operations are performed
+asynchronous so it doesn't add unnecessary latency to the UI.
+
+The SDImageCache class provides a singleton instance for convenience but you can create your own
+instance if you want to create separated cache namespace.
+
+To lookup the cache, you use the `queryDiskCacheForKey:done:` method. If the method returns nil, it means the cache
+doesn't currently own the image. You are thus responsible for generating and caching it. The cache
+key is an application unique identifier for the image to cache. It is generally the absolute URL of
+the image.
+
+```objective-c
+SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
+[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
+{
+    // image is not nil if image was found
+}];
+```
+
+By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache.
+You can prevent this from happening by calling the alternative method `imageFromMemoryCacheForKey:`.
+
+To store an image into the cache, you use the storeImage:forKey: method:
+
+```objective-c
+[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
+```
+
+By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If
+you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative
+third argument.
+
+### Using cache key filter
+
+Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic
+(i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that
+takes the NSURL as input, and output a cache key NSString.
+
+The following example sets a filter in the application delegate that will remove any query-string from
+the URL before to use it as a cache key:
+
+```objective-c
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
+{
+    SDWebImageManager.sharedManager.cacheKeyFilter:^(NSURL *url)
+    {
+        url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
+        return [url absoluteString];
+    };
+
+    // Your app init code...
+    return YES;
+}
+```
+
+
+Common Problems
+---------------
+
+### Using dynamic image size with UITableViewCell
+
+UITableView determins the size of the image by the first image set for a cell. If your remote images
+don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue.
+The following article gives a way to workaround this issue:
+
+[http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/)
+
+
+### Handle image refresh
+
+SDWebImage does very aggressive caching by default. It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. It implies your images URLs are static URLs pointing to images that never change. If the pointed image happen to change, some parts of the URL should change accordingly.
+
+If you don't control the image server you're using, you may not be able to change the URL when its content is updated. This is the case for Facebook avatar URLs for instance. In such case, you may use the `SDWebImageRefreshCached` flag. This will slightly degrade the performance but will respect the HTTP caching control headers:
+
+``` objective-c
+[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
+          placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
+                   options:SDWebImageRefreshCached];
+```
+
+### Add a progress indicator
+
+See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
+
+Installation
+------------
+
+There are three ways to use SDWebImage in your project:
+- using Cocoapods
+- copying all the files into your project
+- importing the project as a static library
+
+### Installation with CocoaPods
+
+[CocoaPods](http://cocoapods.org/) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the [Get Started](http://cocoapods.org/#get_started) section for more details.
+
+#### Podfile
+```
+platform :ios, '6.1'
+pod 'SDWebImage', '~>3.6'
+```
+
+### Add the SDWebImage project to your project
+
+- Download and unzip the last version of the framework from the [download page](https://github.com/rs/SDWebImage/releases)
+- Right-click on the project navigator and select "Add Files to "Your Project":
+- In the dialog, select SDWebImage.framework:
+- Check the "Copy items into destination group's folder (if needed)" checkbox
+
+### Add dependencies
+
+- In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block:
+- Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature:
+
+### Add Linker Flag
+
+Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag:
+
+![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg)
+
+Alternatively, if this causes compilation problems with frameworks that extend optional libraries, such as Parse,  RestKit or opencv2, instead of the -ObjC flag use:
+
+```
+-force_load SDWebImage.framework/Versions/Current/SDWebImage
+```
+
+### Import headers in your source files
+
+In the source files where you need to use the library, import the header file:
+
+```objective-c
+#import <SDWebImage/UIImageView+WebCache.h>
+```
+
+### Build Project
+
+At this point your workspace should build without error. If you are having problem, post to the Issue and the
+community can help you solve it.
+
+Future Enhancements
+-------------------
+
+- LRU memory cache cleanup instead of reset on memory warning
+
+## Licenses
+
+All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE).
diff --git a/SDWebImage/NSData+ImageContentType.h b/SDWebImage/NSData+ImageContentType.h
new file mode 100644
index 0000000..69c76dc
--- /dev/null
+++ b/SDWebImage/NSData+ImageContentType.h
@@ -0,0 +1,26 @@
+//
+// Created by Fabrice Aneche on 06/01/14.
+// Copyright (c) 2014 Dailymotion. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface NSData (ImageContentType)
+
+/**
+ *  Compute the content type for an image data
+ *
+ *  @param data the input data
+ *
+ *  @return the content type as string (i.e. image/jpeg, image/gif)
+ */
++ (NSString *)sd_contentTypeForImageData:(NSData *)data;
+
+@end
+
+
+@interface NSData (ImageContentTypeDeprecated)
+
++ (NSString *)contentTypeForImageData:(NSData *)data __deprecated_msg("Use `sd_contentTypeForImageData:`");
+
+@end
diff --git a/SDWebImage/NSData+ImageContentType.m b/SDWebImage/NSData+ImageContentType.m
new file mode 100644
index 0000000..0941cfa
--- /dev/null
+++ b/SDWebImage/NSData+ImageContentType.m
@@ -0,0 +1,49 @@
+//
+// Created by Fabrice Aneche on 06/01/14.
+// Copyright (c) 2014 Dailymotion. All rights reserved.
+//
+
+#import "NSData+ImageContentType.h"
+
+
+@implementation NSData (ImageContentType)
+
++ (NSString *)sd_contentTypeForImageData:(NSData *)data {
+    uint8_t c;
+    [data getBytes:&c length:1];
+    switch (c) {
+        case 0xFF:
+            return @"image/jpeg";
+        case 0x89:
+            return @"image/png";
+        case 0x47:
+            return @"image/gif";
+        case 0x49:
+        case 0x4D:
+            return @"image/tiff";
+        case 0x52:
+            // R as RIFF for WEBP
+            if ([data length] < 12) {
+                return nil;
+            }
+
+            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
+            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
+                return @"image/webp";
+            }
+
+            return nil;
+    }
+    return nil;
+}
+
+@end
+
+
+@implementation NSData (ImageContentTypeDeprecated)
+
++ (NSString *)contentTypeForImageData:(NSData *)data {
+    return [self sd_contentTypeForImageData:data];
+}
+
+@end
diff --git a/SDWebImage/SDImageCache.h b/SDWebImage/SDImageCache.h
new file mode 100644
index 0000000..bde9d5d
--- /dev/null
+++ b/SDWebImage/SDImageCache.h
@@ -0,0 +1,241 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SDWebImageCompat.h"
+
+typedef NS_ENUM(NSInteger, SDImageCacheType) {
+    /**
+     * The image wasn't available the SDWebImage caches, but was downloaded from the web.
+     */
+    SDImageCacheTypeNone,
+    /**
+     * The image was obtained from the disk cache.
+     */
+    SDImageCacheTypeDisk,
+    /**
+     * The image was obtained from the memory cache.
+     */
+    SDImageCacheTypeMemory
+};
+
+typedef void(^SDWebImageQueryCompletedBlock)(UIImage *image, SDImageCacheType cacheType);
+
+typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache);
+
+typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize);
+
+/**
+ * SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed
+ * asynchronous so it doesn’t add unnecessary latency to the UI.
+ */
+@interface SDImageCache : NSObject
+
+/**
+ * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
+ */
+@property (assign, nonatomic) NSUInteger maxMemoryCost;
+
+/**
+ * The maximum length of time to keep an image in the cache, in seconds
+ */
+@property (assign, nonatomic) NSInteger maxCacheAge;
+
+/**
+ * The maximum size of the cache, in bytes.
+ */
+@property (assign, nonatomic) NSUInteger maxCacheSize;
+
+/**
+ * Returns global shared cache instance
+ *
+ * @return SDImageCache global instance
+ */
++ (SDImageCache *)sharedImageCache;
+
+/**
+ * Init a new cache store with a specific namespace
+ *
+ * @param ns The namespace to use for this cache store
+ */
+- (id)initWithNamespace:(NSString *)ns;
+
+/**
+ * Add a read-only cache path to search for images pre-cached by SDImageCache
+ * Useful if you want to bundle pre-loaded images with your app
+ *
+ * @param path The path to use for this read-only cache path
+ */
+- (void)addReadOnlyCachePath:(NSString *)path;
+
+/**
+ * Store an image into memory and disk cache at the given key.
+ *
+ * @param image The image to store
+ * @param key   The unique image cache key, usually it's image absolute URL
+ */
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key;
+
+/**
+ * Store an image into memory and optionally disk cache at the given key.
+ *
+ * @param image  The image to store
+ * @param key    The unique image cache key, usually it's image absolute URL
+ * @param toDisk Store the image to disk cache if YES
+ */
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
+
+/**
+ * Store an image into memory and optionally disk cache at the given key.
+ *
+ * @param image       The image to store
+ * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
+ * @param imageData   The image data as returned by the server, this representation will be used for disk storage
+ *                    instead of converting the given image object into a storable/compressed image format in order
+ *                    to save quality and CPU
+ * @param key         The unique image cache key, usually it's image absolute URL
+ * @param toDisk      Store the image to disk cache if YES
+ */
+- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
+
+/**
+ * Query the disk cache asynchronously.
+ *
+ * @param key The unique key used to store the wanted image
+ */
+- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
+
+/**
+ * Query the memory cache synchronously.
+ *
+ * @param key The unique key used to store the wanted image
+ */
+- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
+
+/**
+ * Query the disk cache synchronously after checking the memory cache.
+ *
+ * @param key The unique key used to store the wanted image
+ */
+- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
+
+/**
+ * Remove the image from memory and disk cache synchronously
+ *
+ * @param key The unique image cache key
+ */
+- (void)removeImageForKey:(NSString *)key;
+
+
+/**
+ * Remove the image from memory and disk cache synchronously
+ *
+ * @param key             The unique image cache key
+ * @param completionBlock An block that should be executed after the image has been removed (optional)
+ */
+- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
+
+/**
+ * Remove the image from memory and optionally disk cache synchronously
+ *
+ * @param key      The unique image cache key
+ * @param fromDisk Also remove cache entry from disk if YES
+ */
+- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
+
+/**
+ * Remove the image from memory and optionally disk cache synchronously
+ *
+ * @param key             The unique image cache key
+ * @param fromDisk        Also remove cache entry from disk if YES
+ * @param completionBlock An block that should be executed after the image has been removed (optional)
+ */
+- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
+
+/**
+ * Clear all memory cached images
+ */
+- (void)clearMemory;
+
+/**
+ * Clear all disk cached images. Non-blocking method - returns immediately.
+ * @param completionBlock An block that should be executed after cache expiration completes (optional)
+ */
+- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
+
+/**
+ * Clear all disk cached images
+ * @see clearDiskOnCompletion:
+ */
+- (void)clearDisk;
+
+/**
+ * Remove all expired cached image from disk. Non-blocking method - returns immediately.
+ * @param completionBlock An block that should be executed after cache expiration completes (optional)
+ */
+- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
+
+/**
+ * Remove all expired cached image from disk
+ * @see cleanDiskWithCompletionBlock:
+ */
+- (void)cleanDisk;
+
+/**
+ * Get the size used by the disk cache
+ */
+- (NSUInteger)getSize;
+
+/**
+ * Get the number of images in the disk cache
+ */
+- (NSUInteger)getDiskCount;
+
+/**
+ * Asynchronously calculate the disk cache's size.
+ */
+- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock;
+
+/**
+ *  Async check if image exists in disk cache already (does not load the image)
+ *
+ *  @param key             the key describing the url
+ *  @param completionBlock the block to be executed when the check is done.
+ *  @note the completion block will be always executed on the main queue
+ */
+- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
+
+/**
+ *  Check if image exists in disk cache already (does not load the image)
+ *
+ *  @param key the key describing the url
+ *
+ *  @return YES if an image exists for the given key
+ */
+- (BOOL)diskImageExistsWithKey:(NSString *)key;
+
+/**
+ *  Get the cache path for a certain key (needs the cache path root folder)
+ *
+ *  @param key  the key (can be obtained from url using cacheKeyForURL)
+ *  @param path the cach path root folder
+ *
+ *  @return the cache path
+ */
+- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
+
+/**
+ *  Get the default cache path for a certain key
+ *
+ *  @param key the key (can be obtained from url using cacheKeyForURL)
+ *
+ *  @return the default cache path
+ */
+- (NSString *)defaultCachePathForKey:(NSString *)key;
+
+@end
diff --git a/SDWebImage/SDImageCache.m b/SDWebImage/SDImageCache.m
new file mode 100644
index 0000000..59c3471
--- /dev/null
+++ b/SDWebImage/SDImageCache.m
@@ -0,0 +1,534 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDImageCache.h"
+#import "SDWebImageDecoder.h"
+#import "UIImage+MultiFormat.h"
+#import <CommonCrypto/CommonDigest.h>
+
+static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week
+// PNG signature bytes and data (below)
+static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
+static NSData *kPNGSignatureData = nil;
+
+BOOL ImageDataHasPNGPreffix(NSData *data);
+
+BOOL ImageDataHasPNGPreffix(NSData *data) {
+    NSUInteger pngSignatureLength = [kPNGSignatureData length];
+    if ([data length] >= pngSignatureLength) {
+        if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
+            return YES;
+        }
+    }
+
+    return NO;
+}
+
+@interface SDImageCache ()
+
+@property (strong, nonatomic) NSCache *memCache;
+@property (strong, nonatomic) NSString *diskCachePath;
+@property (strong, nonatomic) NSMutableArray *customPaths;
+@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue;
+
+@end
+
+
+@implementation SDImageCache {
+    NSFileManager *_fileManager;
+}
+
++ (SDImageCache *)sharedImageCache {
+    static dispatch_once_t once;
+    static id instance;
+    dispatch_once(&once, ^{
+        instance = [self new];
+        kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];
+    });
+    return instance;
+}
+
+- (id)init {
+    return [self initWithNamespace:@"default"];
+}
+
+- (id)initWithNamespace:(NSString *)ns {
+    if ((self = [super init])) {
+        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
+
+        // Create IO serial queue
+        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
+
+        // Init default values
+        _maxCacheAge = kDefaultCacheMaxCacheAge;
+
+        // Init the memory cache
+        _memCache = [[NSCache alloc] init];
+        _memCache.name = fullNamespace;
+
+        // Init the disk cache
+        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
+        _diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace];
+
+        dispatch_sync(_ioQueue, ^{
+            _fileManager = [NSFileManager new];
+        });
+
+#if TARGET_OS_IPHONE
+        // Subscribe to app events
+        [[NSNotificationCenter defaultCenter] addObserver:self
+                                                 selector:@selector(clearMemory)
+                                                     name:UIApplicationDidReceiveMemoryWarningNotification
+                                                   object:nil];
+
+        [[NSNotificationCenter defaultCenter] addObserver:self
+                                                 selector:@selector(cleanDisk)
+                                                     name:UIApplicationWillTerminateNotification
+                                                   object:nil];
+
+        [[NSNotificationCenter defaultCenter] addObserver:self
+                                                 selector:@selector(backgroundCleanDisk)
+                                                     name:UIApplicationDidEnterBackgroundNotification
+                                                   object:nil];
+#endif
+    }
+
+    return self;
+}
+
+- (void)dealloc {
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+    SDDispatchQueueRelease(_ioQueue);
+}
+
+- (void)addReadOnlyCachePath:(NSString *)path {
+    if (!self.customPaths) {
+        self.customPaths = [NSMutableArray new];
+    }
+
+    if (![self.customPaths containsObject:path]) {
+        [self.customPaths addObject:path];
+    }
+}
+
+- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
+    NSString *filename = [self cachedFileNameForKey:key];
+    return [path stringByAppendingPathComponent:filename];
+}
+
+- (NSString *)defaultCachePathForKey:(NSString *)key {
+    return [self cachePathForKey:key inPath:self.diskCachePath];
+}
+
+#pragma mark SDImageCache (private)
+
+- (NSString *)cachedFileNameForKey:(NSString *)key {
+    const char *str = [key UTF8String];
+    if (str == NULL) {
+        str = "";
+    }
+    unsigned char r[CC_MD5_DIGEST_LENGTH];
+    CC_MD5(str, (CC_LONG)strlen(str), r);
+    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+                                                    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]];
+
+    return filename;
+}
+
+#pragma mark ImageCache
+
+- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
+    if (!image || !key) {
+        return;
+    }
+
+    [self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale];
+
+    if (toDisk) {
+        dispatch_async(self.ioQueue, ^{
+            NSData *data = imageData;
+
+            if (image && (recalculate || !data)) {
+#if TARGET_OS_IPHONE
+                // We need to determine if the image is a PNG or a JPEG
+                // PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html)
+                // The first eight bytes of a PNG file always contain the following (decimal) values:
+                // 137 80 78 71 13 10 26 10
+
+                // We assume the image is PNG, in case the imageData is nil (i.e. if trying to save a UIImage directly),
+                // we will consider it PNG to avoid loosing the transparency
+                BOOL imageIsPng = YES;
+
+                // But if we have an image data, we will look at the preffix
+                if ([imageData length] >= [kPNGSignatureData length]) {
+                    imageIsPng = ImageDataHasPNGPreffix(imageData);
+                }
+
+                if (imageIsPng) {
+                    data = UIImagePNGRepresentation(image);
+                }
+                else {
+                    data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
+                }
+#else
+                data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
+#endif
+            }
+
+            if (data) {
+                if (![_fileManager fileExistsAtPath:_diskCachePath]) {
+                    [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
+                }
+
+                [_fileManager createFileAtPath:[self defaultCachePathForKey:key] contents:data attributes:nil];
+            }
+        });
+    }
+}
+
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
+    [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
+}
+
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
+    [self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
+}
+
+- (BOOL)diskImageExistsWithKey:(NSString *)key {
+    BOOL exists = NO;
+    
+    // this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance
+    // from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely.
+    exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]];
+    
+    return exists;
+}
+
+- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
+    dispatch_async(_ioQueue, ^{
+        BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
+        if (completionBlock) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                completionBlock(exists);
+            });
+        }
+    });
+}
+
+- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
+    return [self.memCache objectForKey:key];
+}
+
+- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
+    // First check the in-memory cache...
+    UIImage *image = [self imageFromMemoryCacheForKey:key];
+    if (image) {
+        return image;
+    }
+
+    // Second check the disk cache...
+    UIImage *diskImage = [self diskImageForKey:key];
+    if (diskImage) {
+        CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale;
+        [self.memCache setObject:diskImage forKey:key cost:cost];
+    }
+
+    return diskImage;
+}
+
+- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
+    NSString *defaultPath = [self defaultCachePathForKey:key];
+    NSData *data = [NSData dataWithContentsOfFile:defaultPath];
+    if (data) {
+        return data;
+    }
+
+    for (NSString *path in self.customPaths) {
+        NSString *filePath = [self cachePathForKey:key inPath:path];
+        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
+        if (imageData) {
+            return imageData;
+        }
+    }
+
+    return nil;
+}
+
+- (UIImage *)diskImageForKey:(NSString *)key {
+    NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
+    if (data) {
+        UIImage *image = [UIImage sd_imageWithData:data];
+        image = [self scaledImageForKey:key image:image];
+        image = [UIImage decodedImageWithImage:image];
+        return image;
+    }
+    else {
+        return nil;
+    }
+}
+
+- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
+    return SDScaledImageForKey(key, image);
+}
+
+- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
+    if (!doneBlock) {
+        return nil;
+    }
+
+    if (!key) {
+        doneBlock(nil, SDImageCacheTypeNone);
+        return nil;
+    }
+
+    // First check the in-memory cache...
+    UIImage *image = [self imageFromMemoryCacheForKey:key];
+    if (image) {
+        doneBlock(image, SDImageCacheTypeMemory);
+        return nil;
+    }
+
+    NSOperation *operation = [NSOperation new];
+    dispatch_async(self.ioQueue, ^{
+        if (operation.isCancelled) {
+            return;
+        }
+
+        @autoreleasepool {
+            UIImage *diskImage = [self diskImageForKey:key];
+            if (diskImage) {
+                CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale;
+                [self.memCache setObject:diskImage forKey:key cost:cost];
+            }
+
+            dispatch_async(dispatch_get_main_queue(), ^{
+                doneBlock(diskImage, SDImageCacheTypeDisk);
+            });
+        }
+    });
+
+    return operation;
+}
+
+- (void)removeImageForKey:(NSString *)key {
+    [self removeImageForKey:key withCompletion:nil];
+}
+
+- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion {
+    [self removeImageForKey:key fromDisk:YES withCompletion:completion];
+}
+
+- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
+    [self removeImageForKey:key fromDisk:fromDisk withCompletion:nil];
+}
+
+- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
+    
+    if (key == nil) {
+        return;
+    }
+    
+    [self.memCache removeObjectForKey:key];
+    
+    if (fromDisk) {
+        dispatch_async(self.ioQueue, ^{
+            [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
+            
+            if (completion) {
+                dispatch_async(dispatch_get_main_queue(), ^{
+                    completion();
+                });
+            }
+        });
+    } else if (completion){
+        completion();
+    }
+    
+}
+
+- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
+    self.memCache.totalCostLimit = maxMemoryCost;
+}
+
+- (NSUInteger)maxMemoryCost {
+    return self.memCache.totalCostLimit;
+}
+
+- (void)clearMemory {
+    [self.memCache removeAllObjects];
+}
+
+- (void)clearDisk {
+    [self clearDiskOnCompletion:nil];
+}
+
+- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion
+{
+    dispatch_async(self.ioQueue, ^{
+        [_fileManager removeItemAtPath:self.diskCachePath error:nil];
+        [_fileManager createDirectoryAtPath:self.diskCachePath
+                withIntermediateDirectories:YES
+                                 attributes:nil
+                                      error:NULL];
+
+        if (completion) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                completion();
+            });
+        }
+    });
+}
+
+- (void)cleanDisk {
+    [self cleanDiskWithCompletionBlock:nil];
+}
+
+- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
+    dispatch_async(self.ioQueue, ^{
+        NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
+        NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
+
+        // This enumerator prefetches useful properties for our cache files.
+        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
+                                                   includingPropertiesForKeys:resourceKeys
+                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
+                                                                 errorHandler:NULL];
+
+        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
+        NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary];
+        NSUInteger currentCacheSize = 0;
+
+        // Enumerate all of the files in the cache directory.  This loop has two purposes:
+        //
+        //  1. Removing files that are older than the expiration date.
+        //  2. Storing file attributes for the size-based cleanup pass.
+        NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init];
+        for (NSURL *fileURL in fileEnumerator) {
+            NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];
+
+            // Skip directories.
+            if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
+                continue;
+            }
+
+            // Remove files that are older than the expiration date;
+            NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
+            if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
+                [urlsToDelete addObject:fileURL];
+                continue;
+            }
+
+            // Store a reference to this file and account for its total size.
+            NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
+            currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
+            [cacheFiles setObject:resourceValues forKey:fileURL];
+        }
+        
+        for (NSURL *fileURL in urlsToDelete) {
+            [_fileManager removeItemAtURL:fileURL error:nil];
+        }
+
+        // If our remaining disk cache exceeds a configured maximum size, perform a second
+        // size-based cleanup pass.  We delete the oldest files first.
+        if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
+            // Target half of our maximum cache size for this cleanup pass.
+            const NSUInteger desiredCacheSize = self.maxCacheSize / 2;
+
+            // Sort the remaining cache files by their last modification time (oldest first).
+            NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
+                                                            usingComparator:^NSComparisonResult(id obj1, id obj2) {
+                                                                return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
+                                                            }];
+
+            // Delete files until we fall below our desired cache size.
+            for (NSURL *fileURL in sortedFiles) {
+                if ([_fileManager removeItemAtURL:fileURL error:nil]) {
+                    NSDictionary *resourceValues = cacheFiles[fileURL];
+                    NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
+                    currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
+
+                    if (currentCacheSize < desiredCacheSize) {
+                        break;
+                    }
+                }
+            }
+        }
+        if (completionBlock) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                completionBlock();
+            });
+        }
+    });
+}
+
+- (void)backgroundCleanDisk {
+    UIApplication *application = [UIApplication sharedApplication];
+    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
+        // Clean up any unfinished task business by marking where you
+        // stopped or ending the task outright.
+        [application endBackgroundTask:bgTask];
+        bgTask = UIBackgroundTaskInvalid;
+    }];
+
+    // Start the long-running task and return immediately.
+    [self cleanDiskWithCompletionBlock:^{
+        [application endBackgroundTask:bgTask];
+        bgTask = UIBackgroundTaskInvalid;
+    }];
+}
+
+- (NSUInteger)getSize {
+    __block NSUInteger size = 0;
+    dispatch_sync(self.ioQueue, ^{
+        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
+        for (NSString *fileName in fileEnumerator) {
+            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
+            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
+            size += [attrs fileSize];
+        }
+    });
+    return size;
+}
+
+- (NSUInteger)getDiskCount {
+    __block NSUInteger count = 0;
+    dispatch_sync(self.ioQueue, ^{
+        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
+        count = [[fileEnumerator allObjects] count];
+    });
+    return count;
+}
+
+- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock {
+    NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
+
+    dispatch_async(self.ioQueue, ^{
+        NSUInteger fileCount = 0;
+        NSUInteger totalSize = 0;
+
+        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
+                                                   includingPropertiesForKeys:@[NSFileSize]
+                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
+                                                                 errorHandler:NULL];
+
+        for (NSURL *fileURL in fileEnumerator) {
+            NSNumber *fileSize;
+            [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
+            totalSize += [fileSize unsignedIntegerValue];
+            fileCount += 1;
+        }
+
+        if (completionBlock) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                completionBlock(fileCount, totalSize);
+            });
+        }
+    });
+}
+
+@end
diff --git a/SDWebImage/SDWebImageCompat.h b/SDWebImage/SDWebImageCompat.h
new file mode 100644
index 0000000..a0555fd
--- /dev/null
+++ b/SDWebImage/SDWebImageCompat.h
@@ -0,0 +1,70 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ * (c) Jamie Pinkham
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <TargetConditionals.h>
+
+#ifdef __OBJC_GC__
+#error SDWebImage does not support Objective-C Garbage Collection
+#endif
+
+#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0
+#error SDWebImage doesn't support Deployement Target version < 5.0
+#endif
+
+#if !TARGET_OS_IPHONE
+#import <AppKit/AppKit.h>
+#ifndef UIImage
+#define UIImage NSImage
+#endif
+#ifndef UIImageView
+#define UIImageView NSImageView
+#endif
+#else
+
+#import <UIKit/UIKit.h>
+
+#endif
+
+#ifndef NS_ENUM
+#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
+#endif
+
+#ifndef NS_OPTIONS
+#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
+#endif
+
+#if OS_OBJECT_USE_OBJC
+    #undef SDDispatchQueueRelease
+    #undef SDDispatchQueueSetterSementics
+    #define SDDispatchQueueRelease(q)
+    #define SDDispatchQueueSetterSementics strong
+#else
+#undef SDDispatchQueueRelease
+#undef SDDispatchQueueSetterSementics
+#define SDDispatchQueueRelease(q) (dispatch_release(q))
+#define SDDispatchQueueSetterSementics assign
+#endif
+
+extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image);
+
+typedef void(^SDWebImageNoParamsBlock)();
+
+#define dispatch_main_sync_safe(block)\
+    if ([NSThread isMainThread]) {\
+        block();\
+    } else {\
+        dispatch_sync(dispatch_get_main_queue(), block);\
+    }
+
+#define dispatch_main_async_safe(block)\
+    if ([NSThread isMainThread]) {\
+        block();\
+    } else {\
+        dispatch_async(dispatch_get_main_queue(), block);\
+    }
diff --git a/SDWebImage/SDWebImageCompat.m b/SDWebImage/SDWebImageCompat.m
new file mode 100644
index 0000000..8c7d345
--- /dev/null
+++ b/SDWebImage/SDWebImageCompat.m
@@ -0,0 +1,45 @@
+//
+//  SDWebImageCompat.m
+//  SDWebImage
+//
+//  Created by Olivier Poitrey on 11/12/12.
+//  Copyright (c) 2012 Dailymotion. All rights reserved.
+//
+
+#import "SDWebImageCompat.h"
+
+#if !__has_feature(objc_arc)
+#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
+#endif
+
+inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
+    if (!image) {
+        return nil;
+    }
+    
+    if ([image.images count] > 0) {
+        NSMutableArray *scaledImages = [NSMutableArray array];
+
+        for (UIImage *tempImage in image.images) {
+            [scaledImages addObject:SDScaledImageForKey(key, tempImage)];
+        }
+
+        return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
+    }
+    else {
+        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
+            CGFloat scale = 1.0;
+            if (key.length >= 8) {
+                // 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)
+                NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
+                if (range.location != NSNotFound) {
+                    scale = 2.0;
+                }
+            }
+
+            UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
+            image = scaledImage;
+        }
+        return image;
+    }
+}
diff --git a/SDWebImage/SDWebImageDecoder.h b/SDWebImage/SDWebImageDecoder.h
new file mode 100644
index 0000000..0176a7b
--- /dev/null
+++ b/SDWebImage/SDWebImageDecoder.h
@@ -0,0 +1,18 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * Created by james <https://github.com/mystcolor> on 9/28/11.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SDWebImageCompat.h"
+
+@interface UIImage (ForceDecode)
+
++ (UIImage *)decodedImageWithImage:(UIImage *)image;
+
+@end
diff --git a/SDWebImage/SDWebImageDecoder.m b/SDWebImage/SDWebImageDecoder.m
new file mode 100644
index 0000000..79ddb30
--- /dev/null
+++ b/SDWebImage/SDWebImageDecoder.m
@@ -0,0 +1,72 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * Created by james <https://github.com/mystcolor> on 9/28/11.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageDecoder.h"
+
+@implementation UIImage (ForceDecode)
+
++ (UIImage *)decodedImageWithImage:(UIImage *)image {
+    if (image.images) {
+        // Do not decode animated images
+        return image;
+    }
+
+    CGImageRef imageRef = image.CGImage;
+    CGSize imageSize = CGSizeMake(CGImageGetWidth(imageRef), CGImageGetHeight(imageRef));
+    CGRect imageRect = (CGRect){.origin = CGPointZero, .size = imageSize};
+
+    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
+
+    int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
+    BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
+            infoMask == kCGImageAlphaNoneSkipFirst ||
+            infoMask == kCGImageAlphaNoneSkipLast);
+
+    // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
+    // https://developer.apple.com/library/mac/#qa/qa1037/_index.html
+    if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) {
+        // Unset the old alpha info.
+        bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+
+        // Set noneSkipFirst.
+        bitmapInfo |= kCGImageAlphaNoneSkipFirst;
+    }
+            // Some PNGs tell us they have alpha but only 3 components. Odd.
+    else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
+        // Unset the old alpha info.
+        bitmapInfo &= ~kCGBitmapAlphaInfoMask;
+        bitmapInfo |= kCGImageAlphaPremultipliedFirst;
+    }
+
+    // It calculates the bytes-per-row based on the bitsPerComponent and width arguments.
+    CGContextRef context = CGBitmapContextCreate(NULL,
+            imageSize.width,
+            imageSize.height,
+            CGImageGetBitsPerComponent(imageRef),
+            0,
+            colorSpace,
+            bitmapInfo);
+    CGColorSpaceRelease(colorSpace);
+
+    // If failed, return undecompressed image
+    if (!context) return image;
+
+    CGContextDrawImage(context, imageRect, imageRef);
+    CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
+
+    CGContextRelease(context);
+
+    UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
+    CGImageRelease(decompressedImageRef);
+    return decompressedImage;
+}
+
+@end
diff --git a/SDWebImage/SDWebImageDownloader.h b/SDWebImage/SDWebImageDownloader.h
new file mode 100644
index 0000000..008231a
--- /dev/null
+++ b/SDWebImage/SDWebImageDownloader.h
@@ -0,0 +1,173 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SDWebImageCompat.h"
+#import "SDWebImageOperation.h"
+
+typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
+    SDWebImageDownloaderLowPriority = 1 << 0,
+    SDWebImageDownloaderProgressiveDownload = 1 << 1,
+
+    /**
+     * By default, request prevent the of NSURLCache. With this flag, NSURLCache
+     * is used with default policies.
+     */
+    SDWebImageDownloaderUseNSURLCache = 1 << 2,
+
+    /**
+     * Call completion block with nil image/imageData if the image was read from NSURLCache
+     * (to be combined with `SDWebImageDownloaderUseNSURLCache`).
+     */
+
+    SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
+    /**
+     * 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.
+     */
+
+    SDWebImageDownloaderContinueInBackground = 1 << 4,
+
+    /**
+     * Handles cookies stored in NSHTTPCookieStore by setting 
+     * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
+     */
+    SDWebImageDownloaderHandleCookies = 1 << 5,
+
+    /**
+     * Enable to allow untrusted SSL ceriticates.
+     * Useful for testing purposes. Use with caution in production.
+     */
+    SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
+
+    /**
+     * Put the image in the high priority queue.
+     */
+    SDWebImageDownloaderHighPriority = 1 << 7,
+    
+
+};
+
+typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
+    /**
+     * Default value. All download operations will execute in queue style (first-in-first-out).
+     */
+    SDWebImageDownloaderFIFOExecutionOrder,
+
+    /**
+     * All download operations will execute in stack style (last-in-first-out).
+     */
+    SDWebImageDownloaderLIFOExecutionOrder
+};
+
+extern NSString *const SDWebImageDownloadStartNotification;
+extern NSString *const SDWebImageDownloadStopNotification;
+
+typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
+
+typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
+
+typedef NSDictionary *(^SDWebImageDownloaderHeadersFilterBlock)(NSURL *url, NSDictionary *headers);
+
+/**
+ * Asynchronous downloader dedicated and optimized for image loading.
+ */
+@interface SDWebImageDownloader : NSObject
+
+@property (assign, nonatomic) NSInteger maxConcurrentDownloads;
+
+/**
+ * Shows the current amount of downloads that still need to be downloaded
+ */
+
+@property (readonly, nonatomic) NSUInteger currentDownloadCount;
+
+
+/**
+ *  The timeout value (in seconds) for the download operation. Default: 15.0.
+ */
+@property (assign, nonatomic) NSTimeInterval downloadTimeout;
+
+
+/**
+ * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`.
+ */
+@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder;
+
+/**
+ *  Singleton method, returns the shared instance
+ *
+ *  @return global shared instance of downloader class
+ */
++ (SDWebImageDownloader *)sharedDownloader;
+
+/**
+ * Set username
+ */
+@property (strong, nonatomic) NSString *username;
+
+/**
+ * Set password
+ */
+@property (strong, nonatomic) NSString *password;
+
+/**
+ * Set filter to pick headers for downloading image HTTP request.
+ *
+ * This block will be invoked for each downloading image request, returned
+ * NSDictionary will be used as headers in corresponding HTTP request.
+ */
+@property (nonatomic, copy) SDWebImageDownloaderHeadersFilterBlock headersFilter;
+
+/**
+ * Set a value for a HTTP header to be appended to each download HTTP request.
+ *
+ * @param value The value for the header field. Use `nil` value to remove the header.
+ * @param field The name of the header field to set.
+ */
+- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
+
+/**
+ * Returns the value of the specified HTTP header field.
+ *
+ * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
+ */
+- (NSString *)valueForHTTPHeaderField:(NSString *)field;
+
+/**
+ * Creates a SDWebImageDownloader async downloader instance with a given URL
+ *
+ * The delegate will be informed when the image is finish downloaded or an error has happen.
+ *
+ * @see SDWebImageDownloaderDelegate
+ *
+ * @param url            The URL to the image to download
+ * @param options        The options to be used for this download
+ * @param progressBlock  A block called repeatedly while the image is downloading
+ * @param completedBlock A block called once the download is completed.
+ *                       If the download succeeded, the image parameter is set, in case of error,
+ *                       error parameter is set with the error. The last parameter is always YES
+ *                       if SDWebImageDownloaderProgressiveDownload isn't use. With the
+ *                       SDWebImageDownloaderProgressiveDownload option, this block is called
+ *                       repeatedly with the partial image object and the finished argument set to NO
+ *                       before to be called a last time with the full image and finished argument
+ *                       set to YES. In case of error, the finished argument is always YES.
+ *
+ * @return A cancellable SDWebImageOperation
+ */
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
+                                         options:(SDWebImageDownloaderOptions)options
+                                        progress:(SDWebImageDownloaderProgressBlock)progressBlock
+                                       completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
+
+/**
+ * Sets the download queue suspension state
+ */
+- (void)setSuspended:(BOOL)suspended;
+
+@end
diff --git a/SDWebImage/SDWebImageDownloader.m b/SDWebImage/SDWebImageDownloader.m
new file mode 100644
index 0000000..60914db
--- /dev/null
+++ b/SDWebImage/SDWebImageDownloader.m
@@ -0,0 +1,225 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageDownloader.h"
+#import "SDWebImageDownloaderOperation.h"
+#import <ImageIO/ImageIO.h>
+
+NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
+NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
+
+static NSString *const kProgressCallbackKey = @"progress";
+static NSString *const kCompletedCallbackKey = @"completed";
+
+@interface SDWebImageDownloader ()
+
+@property (strong, nonatomic) NSOperationQueue *downloadQueue;
+@property (weak, nonatomic) NSOperation *lastAddedOperation;
+@property (strong, nonatomic) NSMutableDictionary *URLCallbacks;
+@property (strong, nonatomic) NSMutableDictionary *HTTPHeaders;
+// This queue is used to serialize the handling of the network responses of all the download operation in a single queue
+@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t barrierQueue;
+
+@end
+
+@implementation SDWebImageDownloader
+
++ (void)initialize {
+    // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator )
+    // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
+    if (NSClassFromString(@"SDNetworkActivityIndicator")) {
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
+        id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
+#pragma clang diagnostic pop
+
+        // Remove observer in case it was previously added.
+        [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil];
+        [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil];
+
+        [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
+                                                 selector:NSSelectorFromString(@"startActivity")
+                                                     name:SDWebImageDownloadStartNotification object:nil];
+        [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
+                                                 selector:NSSelectorFromString(@"stopActivity")
+                                                     name:SDWebImageDownloadStopNotification object:nil];
+    }
+}
+
++ (SDWebImageDownloader *)sharedDownloader {
+    static dispatch_once_t once;
+    static id instance;
+    dispatch_once(&once, ^{
+        instance = [self new];
+    });
+    return instance;
+}
+
+- (id)init {
+    if ((self = [super init])) {
+        _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
+        _downloadQueue = [NSOperationQueue new];
+        _downloadQueue.maxConcurrentOperationCount = 2;
+        _URLCallbacks = [NSMutableDictionary new];
+        _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
+        _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
+        _downloadTimeout = 15.0;
+    }
+    return self;
+}
+
+- (void)dealloc {
+    [self.downloadQueue cancelAllOperations];
+    SDDispatchQueueRelease(_barrierQueue);
+}
+
+- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
+    if (value) {
+        self.HTTPHeaders[field] = value;
+    }
+    else {
+        [self.HTTPHeaders removeObjectForKey:field];
+    }
+}
+
+- (NSString *)valueForHTTPHeaderField:(NSString *)field {
+    return self.HTTPHeaders[field];
+}
+
+- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
+    _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
+}
+
+- (NSUInteger)currentDownloadCount {
+    return _downloadQueue.operationCount;
+}
+
+- (NSInteger)maxConcurrentDownloads {
+    return _downloadQueue.maxConcurrentOperationCount;
+}
+
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageDownloaderCompletedBlock)completedBlock {
+    __block SDWebImageDownloaderOperation *operation;
+    __weak SDWebImageDownloader *wself = self;
+
+    [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
+        NSTimeInterval timeoutInterval = wself.downloadTimeout;
+        if (timeoutInterval == 0.0) {
+            timeoutInterval = 15.0;
+        }
+
+        // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
+        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
+        request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
+        request.HTTPShouldUsePipelining = YES;
+        if (wself.headersFilter) {
+            request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
+        }
+        else {
+            request.allHTTPHeaderFields = wself.HTTPHeaders;
+        }
+        operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request
+                                                                   options:options
+                                                                  progress:^(NSInteger receivedSize, NSInteger expectedSize) {
+                                                                      SDWebImageDownloader *sself = wself;
+                                                                      if (!sself) return;
+                                                                      NSArray *callbacksForURL = [sself callbacksForURL:url];
+                                                                      for (NSDictionary *callbacks in callbacksForURL) {
+                                                                          SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
+                                                                          if (callback) callback(receivedSize, expectedSize);
+                                                                      }
+                                                                  }
+                                                                 completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
+                                                                     SDWebImageDownloader *sself = wself;
+                                                                     if (!sself) return;
+                                                                     NSArray *callbacksForURL = [sself callbacksForURL:url];
+                                                                     if (finished) {
+                                                                         [sself removeCallbacksForURL:url];
+                                                                     }
+                                                                     for (NSDictionary *callbacks in callbacksForURL) {
+                                                                         SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
+                                                                         if (callback) callback(image, data, error, finished);
+                                                                     }
+                                                                 }
+                                                                 cancelled:^{
+                                                                     SDWebImageDownloader *sself = wself;
+                                                                     if (!sself) return;
+                                                                     [sself removeCallbacksForURL:url];
+                                                                 }];
+        
+        if (wself.username && wself.password) {
+            operation.credential = [NSURLCredential credentialWithUser:wself.username password:wself.password persistence:NSURLCredentialPersistenceForSession];
+        }
+        
+        if (options & SDWebImageDownloaderHighPriority) {
+            operation.queuePriority = NSOperationQueuePriorityHigh;
+        } else if (options & SDWebImageDownloaderLowPriority) {
+            operation.queuePriority = NSOperationQueuePriorityLow;
+        }
+
+        [wself.downloadQueue addOperation:operation];
+        if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
+            // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
+            [wself.lastAddedOperation addDependency:operation];
+            wself.lastAddedOperation = operation;
+        }
+    }];
+
+    return operation;
+}
+
+- (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock andCompletedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
+    // 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.
+    if (url == nil) {
+        if (completedBlock != nil) {
+            completedBlock(nil, nil, nil, NO);
+        }
+        return;
+    }
+
+    dispatch_barrier_sync(self.barrierQueue, ^{
+        BOOL first = NO;
+        if (!self.URLCallbacks[url]) {
+            self.URLCallbacks[url] = [NSMutableArray new];
+            first = YES;
+        }
+
+        // Handle single download of simultaneous download request for the same URL
+        NSMutableArray *callbacksForURL = self.URLCallbacks[url];
+        NSMutableDictionary *callbacks = [NSMutableDictionary new];
+        if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
+        if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
+        [callbacksForURL addObject:callbacks];
+        self.URLCallbacks[url] = callbacksForURL;
+
+        if (first) {
+            createCallback();
+        }
+    });
+}
+
+- (NSArray *)callbacksForURL:(NSURL *)url {
+    __block NSArray *callbacksForURL;
+    dispatch_sync(self.barrierQueue, ^{
+        callbacksForURL = self.URLCallbacks[url];
+    });
+    return [callbacksForURL copy];
+}
+
+- (void)removeCallbacksForURL:(NSURL *)url {
+    dispatch_barrier_async(self.barrierQueue, ^{
+        [self.URLCallbacks removeObjectForKey:url];
+    });
+}
+
+- (void)setSuspended:(BOOL)suspended {
+    [self.downloadQueue setSuspended:suspended];
+}
+
+@end
diff --git a/SDWebImage/SDWebImageDownloaderOperation.h b/SDWebImage/SDWebImageDownloaderOperation.h
new file mode 100644
index 0000000..21a3106
--- /dev/null
+++ b/SDWebImage/SDWebImageDownloaderOperation.h
@@ -0,0 +1,60 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SDWebImageDownloader.h"
+#import "SDWebImageOperation.h"
+
+@interface SDWebImageDownloaderOperation : NSOperation <SDWebImageOperation>
+
+/**
+ * The request used by the operation's connection.
+ */
+@property (strong, nonatomic, readonly) NSURLRequest *request;
+
+/**
+ * Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default.
+ *
+ * This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`.
+ */
+@property (nonatomic, assign) BOOL shouldUseCredentialStorage;
+
+/**
+ * The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`.
+ *
+ * This will be overridden by any shared credentials that exist for the username or password of the request URL, if present.
+ */
+@property (nonatomic, strong) NSURLCredential *credential;
+
+/**
+ * The SDWebImageDownloaderOptions for the receiver.
+ */
+@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options;
+
+/**
+ *  Initializes a `SDWebImageDownloaderOperation` object
+ *
+ *  @see SDWebImageDownloaderOperation
+ *
+ *  @param request        the URL request
+ *  @param options        downloader options
+ *  @param progressBlock  the block executed when a new chunk of data arrives. 
+ *                        @note the progress block is executed on a background queue
+ *  @param completedBlock the block executed when the download is done. 
+ *                        @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
+ *  @param cancelBlock    the block executed if the download (operation) is cancelled
+ *
+ *  @return the initialized instance
+ */
+- (id)initWithRequest:(NSURLRequest *)request
+              options:(SDWebImageDownloaderOptions)options
+             progress:(SDWebImageDownloaderProgressBlock)progressBlock
+            completed:(SDWebImageDownloaderCompletedBlock)completedBlock
+            cancelled:(SDWebImageNoParamsBlock)cancelBlock;
+
+@end
diff --git a/SDWebImage/SDWebImageDownloaderOperation.m b/SDWebImage/SDWebImageDownloaderOperation.m
new file mode 100644
index 0000000..333e316
--- /dev/null
+++ b/SDWebImage/SDWebImageDownloaderOperation.m
@@ -0,0 +1,414 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageDownloaderOperation.h"
+#import "SDWebImageDecoder.h"
+#import "UIImage+MultiFormat.h"
+#import <ImageIO/ImageIO.h>
+#import "SDWebImageManager.h"
+
+@interface SDWebImageDownloaderOperation () <NSURLConnectionDataDelegate>
+
+@property (copy, nonatomic) SDWebImageDownloaderProgressBlock progressBlock;
+@property (copy, nonatomic) SDWebImageDownloaderCompletedBlock completedBlock;
+@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
+
+@property (assign, nonatomic, getter = isExecuting) BOOL executing;
+@property (assign, nonatomic, getter = isFinished) BOOL finished;
+@property (assign, nonatomic) NSInteger expectedSize;
+@property (strong, nonatomic) NSMutableData *imageData;
+@property (strong, nonatomic) NSURLConnection *connection;
+@property (strong, atomic) NSThread *thread;
+
+#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
+@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
+#endif
+
+@end
+
+@implementation SDWebImageDownloaderOperation {
+    size_t width, height;
+    UIImageOrientation orientation;
+    BOOL responseFromCached;
+}
+
+@synthesize executing = _executing;
+@synthesize finished = _finished;
+
+- (id)initWithRequest:(NSURLRequest *)request
+              options:(SDWebImageDownloaderOptions)options
+             progress:(SDWebImageDownloaderProgressBlock)progressBlock
+            completed:(SDWebImageDownloaderCompletedBlock)completedBlock
+            cancelled:(SDWebImageNoParamsBlock)cancelBlock {
+    if ((self = [super init])) {
+        _request = request;
+        _shouldUseCredentialStorage = YES;
+        _options = options;
+        _progressBlock = [progressBlock copy];
+        _completedBlock = [completedBlock copy];
+        _cancelBlock = [cancelBlock copy];
+        _executing = NO;
+        _finished = NO;
+        _expectedSize = 0;
+        responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called
+    }
+    return self;
+}
+
+- (void)start {
+    @synchronized (self) {
+        if (self.isCancelled) {
+            self.finished = YES;
+            [self reset];
+            return;
+        }
+
+#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
+        if ([self shouldContinueWhenAppEntersBackground]) {
+            __weak __typeof__ (self) wself = self;
+            self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
+                __strong __typeof (wself) sself = wself;
+
+                if (sself) {
+                    [sself cancel];
+
+                    [[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
+                    sself.backgroundTaskId = UIBackgroundTaskInvalid;
+                }
+            }];
+        }
+#endif
+
+        self.executing = YES;
+        self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
+        self.thread = [NSThread currentThread];
+    }
+
+    [self.connection start];
+
+    if (self.connection) {
+        if (self.progressBlock) {
+            self.progressBlock(0, NSURLResponseUnknownLength);
+        }
+        [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
+
+        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) {
+            // Make sure to run the runloop in our background thread so it can process downloaded data
+            // Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5
+            //       not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466)
+            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
+        }
+        else {
+            CFRunLoopRun();
+        }
+
+        if (!self.isFinished) {
+            [self.connection cancel];
+            [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]];
+        }
+    }
+    else {
+        if (self.completedBlock) {
+            self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES);
+        }
+    }
+
+#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
+    if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
+        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskId];
+        self.backgroundTaskId = UIBackgroundTaskInvalid;
+    }
+#endif
+}
+
+- (void)cancel {
+    @synchronized (self) {
+        if (self.thread) {
+            [self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
+        }
+        else {
+            [self cancelInternal];
+        }
+    }
+}
+
+- (void)cancelInternalAndStop {
+    if (self.isFinished) return;
+    [self cancelInternal];
+    CFRunLoopStop(CFRunLoopGetCurrent());
+}
+
+- (void)cancelInternal {
+    if (self.isFinished) return;
+    [super cancel];
+    if (self.cancelBlock) self.cancelBlock();
+
+    if (self.connection) {
+        [self.connection cancel];
+        [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
+
+        // As we cancelled the connection, its callback won't be called and thus won't
+        // maintain the isFinished and isExecuting flags.
+        if (self.isExecuting) self.executing = NO;
+        if (!self.isFinished) self.finished = YES;
+    }
+
+    [self reset];
+}
+
+- (void)done {
+    self.finished = YES;
+    self.executing = NO;
+    [self reset];
+}
+
+- (void)reset {
+    self.cancelBlock = nil;
+    self.completedBlock = nil;
+    self.progressBlock = nil;
+    self.connection = nil;
+    self.imageData = nil;
+    self.thread = nil;
+}
+
+- (void)setFinished:(BOOL)finished {
+    [self willChangeValueForKey:@"isFinished"];
+    _finished = finished;
+    [self didChangeValueForKey:@"isFinished"];
+}
+
+- (void)setExecuting:(BOOL)executing {
+    [self willChangeValueForKey:@"isExecuting"];
+    _executing = executing;
+    [self didChangeValueForKey:@"isExecuting"];
+}
+
+- (BOOL)isConcurrent {
+    return YES;
+}
+
+#pragma mark NSURLConnection (delegate)
+
+- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
+    if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) {
+        NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
+        self.expectedSize = expected;
+        if (self.progressBlock) {
+            self.progressBlock(0, expected);
+        }
+
+        self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
+    }
+    else {
+        [self.connection cancel];
+
+        [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
+
+        if (self.completedBlock) {
+            self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
+        }
+        CFRunLoopStop(CFRunLoopGetCurrent());
+        [self done];
+    }
+}
+
+- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
+    [self.imageData appendData:data];
+
+    if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) {
+        // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
+        // Thanks to the author @Nyx0uf
+
+        // Get the total bytes downloaded
+        const NSInteger totalSize = self.imageData.length;
+
+        // Update the data source, we must pass ALL the data, not just the new bytes
+        CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL);
+        CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize);
+
+        if (width + height == 0) {
+            CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
+            if (properties) {
+                NSInteger orientationValue = -1;
+                CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
+                if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
+                val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
+                if (val) CFNumberGetValue(val, kCFNumberLongType, &width);
+                val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
+                if (val) CFNumberGetValue(val, kCFNumberNSIntegerType, &orientationValue);
+                CFRelease(properties);
+
+                // When we draw to Core Graphics, we lose orientation information,
+                // which means the image below born of initWithCGIImage will be
+                // oriented incorrectly sometimes. (Unlike the image born of initWithData
+                // in connectionDidFinishLoading.) So save it here and pass it on later.
+                orientation = [[self class] orientationFromPropertyValue:(orientationValue == -1 ? 1 : orientationValue)];
+            }
+
+        }
+
+        if (width + height > 0 && totalSize < self.expectedSize) {
+            // Create the image
+            CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
+
+#ifdef TARGET_OS_IPHONE
+            // Workaround for iOS anamorphic image
+            if (partialImageRef) {
+                const size_t partialHeight = CGImageGetHeight(partialImageRef);
+                CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
+                CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
+                CGColorSpaceRelease(colorSpace);
+                if (bmContext) {
+                    CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
+                    CGImageRelease(partialImageRef);
+                    partialImageRef = CGBitmapContextCreateImage(bmContext);
+                    CGContextRelease(bmContext);
+                }
+                else {
+                    CGImageRelease(partialImageRef);
+                    partialImageRef = nil;
+                }
+            }
+#endif
+
+            if (partialImageRef) {
+                UIImage *image = [UIImage imageWithCGImage:partialImageRef scale:1 orientation:orientation];
+                NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
+                UIImage *scaledImage = [self scaledImageForKey:key image:image];
+                image = [UIImage decodedImageWithImage:scaledImage];
+                CGImageRelease(partialImageRef);
+                dispatch_main_sync_safe(^{
+                    if (self.completedBlock) {
+                        self.completedBlock(image, nil, nil, NO);
+                    }
+                });
+            }
+        }
+
+        CFRelease(imageSource);
+    }
+
+    if (self.progressBlock) {
+        self.progressBlock(self.imageData.length, self.expectedSize);
+    }
+}
+
++ (UIImageOrientation)orientationFromPropertyValue:(NSInteger)value {
+    switch (value) {
+        case 1:
+            return UIImageOrientationUp;
+        case 3:
+            return UIImageOrientationDown;
+        case 8:
+            return UIImageOrientationLeft;
+        case 6:
+            return UIImageOrientationRight;
+        case 2:
+            return UIImageOrientationUpMirrored;
+        case 4:
+            return UIImageOrientationDownMirrored;
+        case 5:
+            return UIImageOrientationLeftMirrored;
+        case 7:
+            return UIImageOrientationRightMirrored;
+        default:
+            return UIImageOrientationUp;
+    }
+}
+
+- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
+    return SDScaledImageForKey(key, image);
+}
+
+- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
+    SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
+    @synchronized(self) {
+        CFRunLoopStop(CFRunLoopGetCurrent());
+        self.thread = nil;
+        self.connection = nil;
+        [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
+    }
+    
+    if (![[NSURLCache sharedURLCache] cachedResponseForRequest:_request]) {
+        responseFromCached = NO;
+    }
+    
+    if (completionBlock)
+    {
+        if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
+            completionBlock(nil, nil, nil, YES);
+        }
+        else {
+            UIImage *image = [UIImage sd_imageWithData:self.imageData];
+            NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL];
+            image = [self scaledImageForKey:key image:image];
+            
+            // Do not force decoding animated GIFs
+            if (!image.images) {
+                image = [UIImage decodedImageWithImage:image];
+            }
+            if (CGSizeEqualToSize(image.size, CGSizeZero)) {
+                completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
+            }
+            else {
+                completionBlock(image, self.imageData, nil, YES);
+            }
+        }
+    }
+    self.completionBlock = nil;
+    [self done];
+}
+
+- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
+    CFRunLoopStop(CFRunLoopGetCurrent());
+    [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
+
+    if (self.completedBlock) {
+        self.completedBlock(nil, nil, error, YES);
+    }
+
+    [self done];
+}
+
+- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
+    responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
+    if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
+        // Prevents caching of responses
+        return nil;
+    }
+    else {
+        return cachedResponse;
+    }
+}
+
+- (BOOL)shouldContinueWhenAppEntersBackground {
+    return self.options & SDWebImageDownloaderContinueInBackground;
+}
+
+- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
+    return self.shouldUseCredentialStorage;
+}
+
+- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
+    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
+        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
+        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
+    } else {
+        if ([challenge previousFailureCount] == 0) {
+            if (self.credential) {
+                [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
+            } else {
+                [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+            }
+        } else {
+            [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
+        }
+    }
+}
+
+@end
diff --git a/SDWebImage/SDWebImageManager.h b/SDWebImage/SDWebImageManager.h
new file mode 100644
index 0000000..6bb0dcf
--- /dev/null
+++ b/SDWebImage/SDWebImageManager.h
@@ -0,0 +1,285 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageCompat.h"
+#import "SDWebImageOperation.h"
+#import "SDWebImageDownloader.h"
+#import "SDImageCache.h"
+
+typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
+    /**
+     * 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.
+     */
+    SDWebImageRetryFailed = 1 << 0,
+
+    /**
+     * By default, image downloads are started during UI interactions, this flags disable this feature,
+     * leading to delayed download on UIScrollView deceleration for instance.
+     */
+    SDWebImageLowPriority = 1 << 1,
+
+    /**
+     * This flag disables on-disk caching
+     */
+    SDWebImageCacheMemoryOnly = 1 << 2,
+
+    /**
+     * 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.
+     */
+    SDWebImageProgressiveDownload = 1 << 3,
+
+    /**
+     * 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.
+     *
+     * Use this flag only if you can't make your URLs static with embeded cache busting parameter.
+     */
+    SDWebImageRefreshCached = 1 << 4,
+
+    /**
+     * 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.
+     */
+    SDWebImageContinueInBackground = 1 << 5,
+
+    /**
+     * Handles cookies stored in NSHTTPCookieStore by setting
+     * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
+     */
+    SDWebImageHandleCookies = 1 << 6,
+
+    /**
+     * Enable to allow untrusted SSL ceriticates.
+     * Useful for testing purposes. Use with caution in production.
+     */
+    SDWebImageAllowInvalidSSLCertificates = 1 << 7,
+
+    /**
+     * 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).
+     */
+    SDWebImageHighPriority = 1 << 8,
+    
+    /**
+     * 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.
+     */
+    SDWebImageDelayPlaceholder = 1 << 9
+};
+
+typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL);
+
+typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);
+
+typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url);
+
+
+@class SDWebImageManager;
+
+@protocol SDWebImageManagerDelegate <NSObject>
+
+@optional
+
+/**
+ * Controls which image should be downloaded when the image is not found in the cache.
+ *
+ * @param imageManager The current `SDWebImageManager`
+ * @param imageURL     The url of the image to be downloaded
+ *
+ * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
+ */
+- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL;
+
+/**
+ * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
+ * NOTE: This method is called from a global queue in order to not to block the main thread.
+ *
+ * @param imageManager The current `SDWebImageManager`
+ * @param image        The image to transform
+ * @param imageURL     The url of the image to transform
+ *
+ * @return The transformed image object.
+ */
+- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;
+
+@end
+
+/**
+ * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
+ * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
+ * You can use this class directly to benefit from web image downloading with caching in another context than
+ * a UIView.
+ *
+ * Here is a simple example of how to use SDWebImageManager:
+ *
+ * @code
+
+SDWebImageManager *manager = [SDWebImageManager sharedManager];
+[manager downloadWithURL:imageURL
+                 options:0
+                progress:nil
+               completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+                   if (image) {
+                       // do something with image
+                   }
+               }];
+
+ * @endcode
+ */
+@interface SDWebImageManager : NSObject
+
+@property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate;
+
+@property (strong, nonatomic, readonly) SDImageCache *imageCache;
+@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;
+
+/**
+ * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
+ * be used to remove dynamic part of an image URL.
+ *
+ * The following example sets a filter in the application delegate that will remove any query-string from the
+ * URL before to use it as a cache key:
+ *
+ * @code
+
+[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
+    url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
+    return [url absoluteString];
+}];
+
+ * @endcode
+ */
+@property (copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
+
+/**
+ * Returns global SDWebImageManager instance.
+ *
+ * @return SDWebImageManager shared instance
+ */
++ (SDWebImageManager *)sharedManager;
+
+/**
+ * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
+ *
+ * @param url            The URL to the image
+ * @param options        A mask to specify options to use for this request
+ * @param progressBlock  A block called while image is downloading
+ * @param completedBlock A block called when operation has been completed.
+ *
+ *   This parameter is required.
+ * 
+ *   This block has no return value and takes the requested UIImage as first parameter.
+ *   In case of error the image parameter is nil and the second parameter may contain an NSError.
+ *
+ *   The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache
+ *   or from the memory cache or from the network.
+ *
+ *   The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is 
+ *   downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the
+ *   block is called a last time with the full image and the last parameter set to YES.
+ *
+ * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
+ */
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
+                                         options:(SDWebImageOptions)options
+                                        progress:(SDWebImageDownloaderProgressBlock)progressBlock
+                                       completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
+
+/**
+ * Saves image to cache for given URL
+ *
+ * @param image The image to cache
+ * @param url   The URL to the image
+ *
+ */
+
+- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url;
+
+/**
+ * Cancel all current opreations
+ */
+- (void)cancelAll;
+
+/**
+ * Check one or more operations running
+ */
+- (BOOL)isRunning;
+
+/**
+ *  Check if image has already been cached
+ *
+ *  @param url image url
+ *
+ *  @return if the image was already cached
+ */
+- (BOOL)cachedImageExistsForURL:(NSURL *)url;
+
+/**
+ *  Check if image has already been cached on disk only
+ *
+ *  @param url image url
+ *
+ *  @return if the image was already cached (disk only)
+ */
+- (BOOL)diskImageExistsForURL:(NSURL *)url;
+
+/**
+ *  Async check if image has already been cached
+ *
+ *  @param url              image url
+ *  @param completionBlock  the block to be executed when the check is finished
+ *  
+ *  @note the completion block is always executed on the main queue
+ */
+- (void)cachedImageExistsForURL:(NSURL *)url
+                     completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
+
+/**
+ *  Async check if image has already been cached on disk only
+ *
+ *  @param url              image url
+ *  @param completionBlock  the block to be executed when the check is finished
+ *
+ *  @note the completion block is always executed on the main queue
+ */
+- (void)diskImageExistsForURL:(NSURL *)url
+                   completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
+
+
+/**
+ *Return the cache key for a given URL
+ */
+- (NSString *)cacheKeyForURL:(NSURL *)url;
+
+@end
+
+
+#pragma mark - Deprecated
+
+typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`");
+typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`");
+
+
+@interface SDWebImageManager (Deprecated)
+
+/**
+ *  Downloads the image at the given URL if not present in cache or return the cached version otherwise.
+ *
+ *  @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:`
+ */
+- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url
+                                    options:(SDWebImageOptions)options
+                                   progress:(SDWebImageDownloaderProgressBlock)progressBlock
+                                  completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`");
+
+@end
diff --git a/SDWebImage/SDWebImageManager.m b/SDWebImage/SDWebImageManager.m
new file mode 100644
index 0000000..2781ec8
--- /dev/null
+++ b/SDWebImage/SDWebImageManager.m
@@ -0,0 +1,346 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageManager.h"
+#import <objc/message.h>
+
+@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
+
+@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
+@property (copy, nonatomic) SDWebImageNoParamsBlock cancelBlock;
+@property (strong, nonatomic) NSOperation *cacheOperation;
+
+@end
+
+@interface SDWebImageManager ()
+
+@property (strong, nonatomic, readwrite) SDImageCache *imageCache;
+@property (strong, nonatomic, readwrite) SDWebImageDownloader *imageDownloader;
+@property (strong, nonatomic) NSMutableArray *failedURLs;
+@property (strong, nonatomic) NSMutableArray *runningOperations;
+
+@end
+
+@implementation SDWebImageManager
+
++ (id)sharedManager {
+    static dispatch_once_t once;
+    static id instance;
+    dispatch_once(&once, ^{
+        instance = [self new];
+    });
+    return instance;
+}
+
+- (id)init {
+    if ((self = [super init])) {
+        _imageCache = [self createCache];
+        _imageDownloader = [SDWebImageDownloader sharedDownloader];
+        _failedURLs = [NSMutableArray new];
+        _runningOperations = [NSMutableArray new];
+    }
+    return self;
+}
+
+- (SDImageCache *)createCache {
+    return [SDImageCache sharedImageCache];
+}
+
+- (NSString *)cacheKeyForURL:(NSURL *)url {
+    if (self.cacheKeyFilter) {
+        return self.cacheKeyFilter(url);
+    }
+    else {
+        return [url absoluteString];
+    }
+}
+
+- (BOOL)cachedImageExistsForURL:(NSURL *)url {
+    NSString *key = [self cacheKeyForURL:url];
+    if ([self.imageCache imageFromMemoryCacheForKey:key] != nil) return YES;
+    return [self.imageCache diskImageExistsWithKey:key];
+}
+
+- (BOOL)diskImageExistsForURL:(NSURL *)url {
+    NSString *key = [self cacheKeyForURL:url];
+    return [self.imageCache diskImageExistsWithKey:key];
+}
+
+- (void)cachedImageExistsForURL:(NSURL *)url
+                     completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
+    NSString *key = [self cacheKeyForURL:url];
+    
+    BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
+    
+    if (isInMemoryCache) {
+        // making sure we call the completion block on the main queue
+        dispatch_async(dispatch_get_main_queue(), ^{
+            if (completionBlock) {
+                completionBlock(YES);
+            }
+        });
+        return;
+    }
+    
+    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
+        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
+        if (completionBlock) {
+            completionBlock(isInDiskCache);
+        }
+    }];
+}
+
+- (void)diskImageExistsForURL:(NSURL *)url
+                   completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
+    NSString *key = [self cacheKeyForURL:url];
+    
+    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
+        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
+        if (completionBlock) {
+            completionBlock(isInDiskCache);
+        }
+    }];
+}
+
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
+                                         options:(SDWebImageOptions)options
+                                        progress:(SDWebImageDownloaderProgressBlock)progressBlock
+                                       completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
+    // Invoking this method without a completedBlock is pointless
+    NSParameterAssert(completedBlock);
+
+    // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
+    // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
+    if ([url isKindOfClass:NSString.class]) {
+        url = [NSURL URLWithString:(NSString *)url];
+    }
+
+    // Prevents app crashing on argument type error like sending NSNull instead of NSURL
+    if (![url isKindOfClass:NSURL.class]) {
+        url = nil;
+    }
+
+    __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
+    __weak SDWebImageCombinedOperation *weakOperation = operation;
+
+    BOOL isFailedUrl = NO;
+    @synchronized (self.failedURLs) {
+        isFailedUrl = [self.failedURLs containsObject:url];
+    }
+
+    if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
+        dispatch_main_sync_safe(^{
+            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
+            completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
+        });
+        return operation;
+    }
+
+    @synchronized (self.runningOperations) {
+        [self.runningOperations addObject:operation];
+    }
+    NSString *key = [self cacheKeyForURL:url];
+
+    operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
+        if (operation.isCancelled) {
+            @synchronized (self.runningOperations) {
+                [self.runningOperations removeObject:operation];
+            }
+
+            return;
+        }
+
+        if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
+            if (image && options & SDWebImageRefreshCached) {
+                dispatch_main_sync_safe(^{
+                    // If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image
+                    // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
+                    completedBlock(image, nil, cacheType, YES, url);
+                });
+            }
+
+            // download if no image or requested to refresh anyway, and download allowed by delegate
+            SDWebImageDownloaderOptions downloaderOptions = 0;
+            if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
+            if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
+            if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
+            if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
+            if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
+            if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
+            if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
+            if (image && options & SDWebImageRefreshCached) {
+                // force progressive off if image already cached but forced refreshing
+                downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
+                // ignore image read from NSURLCache if image if cached but force refreshing
+                downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
+            }
+            id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
+                if (weakOperation.isCancelled) {
+                    // Do nothing if the operation was cancelled
+                    // See #699 for more details
+                    // 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
+                }
+                else if (error) {
+                    dispatch_main_sync_safe(^{
+                        if (!weakOperation.isCancelled) {
+                            completedBlock(nil, error, SDImageCacheTypeNone, finished, url);
+                        }
+                    });
+
+                    if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) {
+                        @synchronized (self.failedURLs) {
+                            [self.failedURLs addObject:url];
+                        }
+                    }
+                }
+                else {
+                    BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
+
+                    if (options & SDWebImageRefreshCached && image && !downloadedImage) {
+                        // Image refresh hit the NSURLCache cache, do not call the completion block
+                    }
+                            // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it
+                    else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
+                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
+                            UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
+
+                            if (transformedImage && finished) {
+                                BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
+                                [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
+                            }
+
+                            dispatch_main_sync_safe(^{
+                                if (!weakOperation.isCancelled) {
+                                    completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished, url);
+                                }
+                            });
+                        });
+                    }
+                    else {
+                        if (downloadedImage && finished) {
+                            [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
+                        }
+
+                        dispatch_main_sync_safe(^{
+                            if (!weakOperation.isCancelled) {
+                                completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
+                            }
+                        });
+                    }
+                }
+
+                if (finished) {
+                    @synchronized (self.runningOperations) {
+                        [self.runningOperations removeObject:operation];
+                    }
+                }
+            }];
+            operation.cancelBlock = ^{
+                [subOperation cancel];
+                
+                @synchronized (self.runningOperations) {
+                    [self.runningOperations removeObject:weakOperation];
+                }
+            };
+        }
+        else if (image) {
+            dispatch_main_sync_safe(^{
+                if (!weakOperation.isCancelled) {
+                    completedBlock(image, nil, cacheType, YES, url);
+                }
+            });
+            @synchronized (self.runningOperations) {
+                [self.runningOperations removeObject:operation];
+            }
+        }
+        else {
+            // Image not in cache and download disallowed by delegate
+            dispatch_main_sync_safe(^{
+                if (!weakOperation.isCancelled) {
+                    completedBlock(nil, nil, SDImageCacheTypeNone, YES, url);
+                }
+            });
+            @synchronized (self.runningOperations) {
+                [self.runningOperations removeObject:operation];
+            }
+        }
+    }];
+
+    return operation;
+}
+
+- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url {
+    if (image && url) {
+        NSString *key = [self cacheKeyForURL:url];
+        [self.imageCache storeImage:image forKey:key toDisk:YES];
+    }
+}
+
+- (void)cancelAll {
+    @synchronized (self.runningOperations) {
+        [self.runningOperations makeObjectsPerformSelector:@selector(cancel)];
+        [self.runningOperations removeAllObjects];
+    }
+}
+
+- (BOOL)isRunning {
+    return self.runningOperations.count > 0;
+}
+
+@end
+
+
+@implementation SDWebImageCombinedOperation
+
+- (void)setCancelBlock:(SDWebImageNoParamsBlock)cancelBlock {
+    // check if the operation is already cancelled, then we just call the cancelBlock
+    if (self.isCancelled) {
+        if (cancelBlock) {
+            cancelBlock();
+        }
+        _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
+    } else {
+        _cancelBlock = [cancelBlock copy];
+    }
+}
+
+- (void)cancel {
+    self.cancelled = YES;
+    if (self.cacheOperation) {
+        [self.cacheOperation cancel];
+        self.cacheOperation = nil;
+    }
+    if (self.cancelBlock) {
+        self.cancelBlock();
+        
+        // TODO: this is a temporary fix to #809.
+        // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
+//        self.cancelBlock = nil;
+        _cancelBlock = nil;
+    }
+}
+
+@end
+
+
+@implementation SDWebImageManager (Deprecated)
+
+// deprecated method, uses the non deprecated method
+// adapter for the completion block
+- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock {
+    return [self downloadImageWithURL:url
+                              options:options
+                             progress:progressBlock
+                            completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+                                if (completedBlock) {
+                                    completedBlock(image, error, cacheType, finished);
+                                }
+                            }];
+}
+
+@end
diff --git a/SDWebImage/SDWebImageOperation.h b/SDWebImage/SDWebImageOperation.h
new file mode 100644
index 0000000..71094ee
--- /dev/null
+++ b/SDWebImage/SDWebImageOperation.h
@@ -0,0 +1,15 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+
+@protocol SDWebImageOperation <NSObject>
+
+- (void)cancel;
+
+@end
diff --git a/SDWebImage/SDWebImagePrefetcher.h b/SDWebImage/SDWebImagePrefetcher.h
new file mode 100644
index 0000000..4f14fa2
--- /dev/null
+++ b/SDWebImage/SDWebImagePrefetcher.h
@@ -0,0 +1,98 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <Foundation/Foundation.h>
+#import "SDWebImageManager.h"
+
+@class SDWebImagePrefetcher;
+
+@protocol SDWebImagePrefetcherDelegate <NSObject>
+
+@optional
+
+/**
+ * Called when an image was prefetched.
+ *
+ * @param imagePrefetcher The current image prefetcher
+ * @param imageURL        The image url that was prefetched
+ * @param finishedCount   The total number of images that were prefetched (successful or not)
+ * @param totalCount      The total number of images that were to be prefetched
+ */
+- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount;
+
+/**
+ * Called when all images are prefetched.
+ * @param imagePrefetcher The current image prefetcher
+ * @param totalCount      The total number of images that were prefetched (whether successful or not)
+ * @param skippedCount    The total number of images that were skipped
+ */
+- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount;
+
+@end
+
+typedef void(^SDWebImagePrefetcherProgressBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfTotalUrls);
+typedef void(^SDWebImagePrefetcherCompletionBlock)(NSUInteger noOfFinishedUrls, NSUInteger noOfSkippedUrls);
+
+/**
+ * Prefetch some URLs in the cache for future use. Images are downloaded in low priority.
+ */
+@interface SDWebImagePrefetcher : NSObject
+
+/**
+ *  The web image manager
+ */
+@property (strong, nonatomic, readonly) SDWebImageManager *manager;
+
+/**
+ * Maximum number of URLs to prefetch at the same time. Defaults to 3.
+ */
+@property (nonatomic, assign) NSUInteger maxConcurrentDownloads;
+
+/**
+ * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority.
+ */
+@property (nonatomic, assign) SDWebImageOptions options;
+
+@property (weak, nonatomic) id <SDWebImagePrefetcherDelegate> delegate;
+
+/**
+ * Return the global image prefetcher instance.
+ */
++ (SDWebImagePrefetcher *)sharedImagePrefetcher;
+
+/**
+ * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
+ * currently one image is downloaded at a time,
+ * and skips images for failed downloads and proceed to the next image in the list
+ *
+ * @param urls list of URLs to prefetch
+ */
+- (void)prefetchURLs:(NSArray *)urls;
+
+/**
+ * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching,
+ * currently one image is downloaded at a time,
+ * and skips images for failed downloads and proceed to the next image in the list
+ *
+ * @param urls            list of URLs to prefetch
+ * @param progressBlock   block to be called when progress updates; 
+ *                        first parameter is the number of completed (successful or not) requests, 
+ *                        second parameter is the total number of images originally requested to be prefetched
+ * @param completionBlock block to be called when prefetching is completed
+ *                        first param is the number of completed (successful or not) requests,
+ *                        second parameter is the number of skipped requests
+ */
+- (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock;
+
+/**
+ * Remove and cancel queued list
+ */
+- (void)cancelPrefetching;
+
+
+@end
diff --git a/SDWebImage/SDWebImagePrefetcher.m b/SDWebImage/SDWebImagePrefetcher.m
new file mode 100644
index 0000000..4087e4a
--- /dev/null
+++ b/SDWebImage/SDWebImagePrefetcher.m
@@ -0,0 +1,138 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImagePrefetcher.h"
+
+#if !defined(DEBUG) && !defined (SD_VERBOSE)
+#define NSLog(...)
+#endif
+
+@interface SDWebImagePrefetcher ()
+
+@property (strong, nonatomic) SDWebImageManager *manager;
+@property (strong, nonatomic) NSArray *prefetchURLs;
+@property (assign, nonatomic) NSUInteger requestedCount;
+@property (assign, nonatomic) NSUInteger skippedCount;
+@property (assign, nonatomic) NSUInteger finishedCount;
+@property (assign, nonatomic) NSTimeInterval startedTime;
+@property (copy, nonatomic) SDWebImagePrefetcherCompletionBlock completionBlock;
+@property (copy, nonatomic) SDWebImagePrefetcherProgressBlock progressBlock;
+
+@end
+
+@implementation SDWebImagePrefetcher
+
++ (SDWebImagePrefetcher *)sharedImagePrefetcher {
+    static dispatch_once_t once;
+    static id instance;
+    dispatch_once(&once, ^{
+        instance = [self new];
+    });
+    return instance;
+}
+
+- (id)init {
+    if ((self = [super init])) {
+        _manager = [SDWebImageManager new];
+        _options = SDWebImageLowPriority;
+        self.maxConcurrentDownloads = 3;
+    }
+    return self;
+}
+
+- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads {
+    self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads;
+}
+
+- (NSUInteger)maxConcurrentDownloads {
+    return self.manager.imageDownloader.maxConcurrentDownloads;
+}
+
+- (void)startPrefetchingAtIndex:(NSUInteger)index {
+    if (index >= self.prefetchURLs.count) return;
+    self.requestedCount++;
+    [self.manager downloadImageWithURL:self.prefetchURLs[index] options:self.options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+        if (!finished) return;
+        self.finishedCount++;
+
+        if (image) {
+            if (self.progressBlock) {
+                self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
+            }
+            NSLog(@"Prefetched %@ out of %@", @(self.finishedCount), @(self.prefetchURLs.count));
+        }
+        else {
+            if (self.progressBlock) {
+                self.progressBlock(self.finishedCount,[self.prefetchURLs count]);
+            }
+            NSLog(@"Prefetched %@ out of %@ (Failed)", @(self.finishedCount), @(self.prefetchURLs.count));
+
+            // Add last failed
+            self.skippedCount++;
+        }
+        if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) {
+            [self.delegate imagePrefetcher:self
+                            didPrefetchURL:self.prefetchURLs[index]
+                             finishedCount:self.finishedCount
+                                totalCount:self.prefetchURLs.count
+            ];
+        }
+
+        if (self.prefetchURLs.count > self.requestedCount) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+                [self startPrefetchingAtIndex:self.requestedCount];
+            });
+        }
+        else if (self.finishedCount == self.requestedCount) {
+            [self reportStatus];
+            if (self.completionBlock) {
+                self.completionBlock(self.finishedCount, self.skippedCount);
+                self.completionBlock = nil;
+            }
+        }
+    }];
+}
+
+- (void)reportStatus {
+    NSUInteger total = [self.prefetchURLs count];
+    NSLog(@"Finished prefetching (%@ successful, %@ skipped, timeElasped %.2f)", @(total - self.skippedCount), @(self.skippedCount), CFAbsoluteTimeGetCurrent() - self.startedTime);
+    if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) {
+        [self.delegate imagePrefetcher:self
+               didFinishWithTotalCount:(total - self.skippedCount)
+                          skippedCount:self.skippedCount
+        ];
+    }
+}
+
+- (void)prefetchURLs:(NSArray *)urls {
+    [self prefetchURLs:urls progress:nil completed:nil];
+}
+
+- (void)prefetchURLs:(NSArray *)urls progress:(SDWebImagePrefetcherProgressBlock)progressBlock completed:(SDWebImagePrefetcherCompletionBlock)completionBlock {
+    [self cancelPrefetching]; // Prevent duplicate prefetch request
+    self.startedTime = CFAbsoluteTimeGetCurrent();
+    self.prefetchURLs = urls;
+    self.completionBlock = completionBlock;
+    self.progressBlock = progressBlock;
+
+    // Starts prefetching from the very first image on the list with the max allowed concurrency
+    NSUInteger listCount = self.prefetchURLs.count;
+    for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) {
+        [self startPrefetchingAtIndex:i];
+    }
+}
+
+- (void)cancelPrefetching {
+    self.prefetchURLs = nil;
+    self.skippedCount = 0;
+    self.requestedCount = 0;
+    self.finishedCount = 0;
+    [self.manager cancelAll];
+}
+
+@end
diff --git a/SDWebImage/UIButton+WebCache.h b/SDWebImage/UIButton+WebCache.h
new file mode 100644
index 0000000..7a6e867
--- /dev/null
+++ b/SDWebImage/UIButton+WebCache.h
@@ -0,0 +1,229 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageCompat.h"
+#import "SDWebImageManager.h"
+
+/**
+ * Integrates SDWebImage async downloading and caching of remote images with UIButtonView.
+ */
+@interface UIButton (WebCache)
+
+/**
+ * Get the current image URL.
+ */
+- (NSURL *)sd_currentImageURL;
+
+/**
+ * Get the image URL for a control state.
+ * 
+ * @param state Which state you want to know the URL for. The values are described in UIControlState.
+ */
+- (NSURL *)sd_imageURLForState:(UIControlState)state;
+
+/**
+ * Set the imageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url   The url for the image.
+ * @param state The state that uses the specified title. The values are described in UIControlState.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state;
+
+/**
+ * Set the imageView `image` with an `url` and a placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param state       The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @see sd_setImageWithURL:placeholderImage:options:
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param state       The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @param options     The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
+
+/**
+ * Set the imageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param state          The state that uses the specified title. The values are described in UIControlState.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param state          The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param state          The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the backgroundImageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url   The url for the image.
+ * @param state The state that uses the specified title. The values are described in UIControlState.
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
+
+/**
+ * Set the backgroundImageView `image` with an `url` and a placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param state       The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @see sd_setImageWithURL:placeholderImage:options:
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
+
+/**
+ * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param state       The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @param options     The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
+
+/**
+ * Set the backgroundImageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param state          The state that uses the specified title. The values are described in UIControlState.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the backgroundImageView `image` with an `url`, placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param state          The state that uses the specified title. The values are described in UIControlState.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the backgroundImageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Cancel the current image download
+ */
+- (void)sd_cancelImageLoadForState:(UIControlState)state;
+
+/**
+ * Cancel the current backgroundImage download
+ */
+- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;
+
+@end
+
+
+@interface UIButton (WebCacheDeprecated)
+
+- (NSURL *)currentImageURL __deprecated_msg("Use `sd_currentImageURL`");
+- (NSURL *)imageURLForState:(UIControlState)state __deprecated_msg("Use `sd_imageURLForState:`");
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:`");
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:`");
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:`");
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:completed:`");
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:completed:`");
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:forState:placeholderImage:options:completed:`");
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:`");
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:`");
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:`");
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:completed:`");
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:completed:`");
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setBackgroundImageWithURL:forState:placeholderImage:options:completed:`");
+
+- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelImageLoadForState:`");
+- (void)cancelBackgroundImageLoadForState:(UIControlState)state __deprecated_msg("Use `sd_cancelBackgroundImageLoadForState:`");
+
+@end
diff --git a/SDWebImage/UIButton+WebCache.m b/SDWebImage/UIButton+WebCache.m
new file mode 100644
index 0000000..8e076ae
--- /dev/null
+++ b/SDWebImage/UIButton+WebCache.m
@@ -0,0 +1,260 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "UIButton+WebCache.h"
+#import "objc/runtime.h"
+#import "UIView+WebCacheOperation.h"
+
+static char imageURLStorageKey;
+
+@implementation UIButton (WebCache)
+
+- (NSURL *)sd_currentImageURL {
+    NSURL *url = self.imageURLStorage[@(self.state)];
+
+    if (!url) {
+        url = self.imageURLStorage[@(UIControlStateNormal)];
+    }
+
+    return url;
+}
+
+- (NSURL *)sd_imageURLForState:(UIControlState)state {
+    return self.imageURLStorage[@(state)];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
+    [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
+
+    [self setImage:placeholder forState:state];
+    [self sd_cancelImageLoadForState:state];
+    
+    if (!url) {
+        [self.imageURLStorage removeObjectForKey:@(state)];
+        
+        dispatch_main_async_safe(^{
+            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
+            if (completedBlock) {
+                completedBlock(nil, error, SDImageCacheTypeNone, url);
+            }
+        });
+        
+        return;
+    }
+    
+    self.imageURLStorage[@(state)] = url;
+
+    __weak UIButton *wself = self;
+    id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+        if (!wself) return;
+        dispatch_main_sync_safe(^{
+            __strong UIButton *sself = wself;
+            if (!sself) return;
+            if (image) {
+                [sself setImage:image forState:state];
+            }
+            if (completedBlock && finished) {
+                completedBlock(image, error, cacheType, url);
+            }
+        });
+    }];
+    [self sd_setImageLoadOperation:operation forState:state];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
+}
+
+- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_cancelImageLoadForState:state];
+
+    [self setBackgroundImage:placeholder forState:state];
+
+    if (url) {
+        __weak UIButton *wself = self;
+        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+            if (!wself) return;
+            dispatch_main_sync_safe(^{
+                __strong UIButton *sself = wself;
+                if (!sself) return;
+                if (image) {
+                    [sself setBackgroundImage:image forState:state];
+                }
+                if (completedBlock && finished) {
+                    completedBlock(image, error, cacheType, url);
+                }
+            });
+        }];
+        [self sd_setBackgroundImageLoadOperation:operation forState:state];
+    } else {
+        dispatch_main_async_safe(^{
+            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
+            if (completedBlock) {
+                completedBlock(nil, error, SDImageCacheTypeNone, url);
+            }
+        });
+    }
+}
+
+- (void)sd_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
+    [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
+}
+
+- (void)sd_cancelImageLoadForState:(UIControlState)state {
+    [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
+}
+
+- (void)sd_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
+    [self sd_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
+}
+
+- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state {
+    [self sd_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
+}
+
+- (NSMutableDictionary *)imageURLStorage {
+    NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
+    if (!storage)
+    {
+        storage = [NSMutableDictionary dictionary];
+        objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    }
+
+    return storage;
+}
+
+@end
+
+
+@implementation UIButton (WebCacheDeprecated)
+
+- (NSURL *)currentImageURL {
+    return [self sd_currentImageURL];
+}
+
+- (NSURL *)imageURLForState:(UIControlState)state {
+    return [self sd_imageURLForState:state];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state {
+    [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)cancelCurrentImageLoad {
+    // in a backwards compatible manner, cancel for current state
+    [self sd_cancelImageLoadForState:self.state];
+}
+
+- (void)cancelBackgroundImageLoadForState:(UIControlState)state {
+    [self sd_cancelBackgroundImageLoadForState:state];
+}
+
+@end
diff --git a/SDWebImage/UIImage+GIF.h b/SDWebImage/UIImage+GIF.h
new file mode 100755
index 0000000..084f424
--- /dev/null
+++ b/SDWebImage/UIImage+GIF.h
@@ -0,0 +1,19 @@
+//
+//  UIImage+GIF.h
+//  LBGIFImage
+//
+//  Created by Laurin Brandner on 06.01.12.
+//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface UIImage (GIF)
+
++ (UIImage *)sd_animatedGIFNamed:(NSString *)name;
+
++ (UIImage *)sd_animatedGIFWithData:(NSData *)data;
+
+- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size;
+
+@end
diff --git a/SDWebImage/UIImage+GIF.m b/SDWebImage/UIImage+GIF.m
new file mode 100755
index 0000000..a703637
--- /dev/null
+++ b/SDWebImage/UIImage+GIF.m
@@ -0,0 +1,158 @@
+//
+//  UIImage+GIF.m
+//  LBGIFImage
+//
+//  Created by Laurin Brandner on 06.01.12.
+//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
+//
+
+#import "UIImage+GIF.h"
+#import <ImageIO/ImageIO.h>
+
+@implementation UIImage (GIF)
+
++ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
+    if (!data) {
+        return nil;
+    }
+
+    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
+
+    size_t count = CGImageSourceGetCount(source);
+
+    UIImage *animatedImage;
+
+    if (count <= 1) {
+        animatedImage = [[UIImage alloc] initWithData:data];
+    }
+    else {
+        NSMutableArray *images = [NSMutableArray array];
+
+        NSTimeInterval duration = 0.0f;
+
+        for (size_t i = 0; i < count; i++) {
+            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
+
+            duration += [self sd_frameDurationAtIndex:i source:source];
+
+            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
+
+            CGImageRelease(image);
+        }
+
+        if (!duration) {
+            duration = (1.0f / 10.0f) * count;
+        }
+
+        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
+    }
+
+    CFRelease(source);
+
+    return animatedImage;
+}
+
++ (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
+    float frameDuration = 0.1f;
+    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
+    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
+    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
+
+    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
+    if (delayTimeUnclampedProp) {
+        frameDuration = [delayTimeUnclampedProp floatValue];
+    }
+    else {
+
+        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
+        if (delayTimeProp) {
+            frameDuration = [delayTimeProp floatValue];
+        }
+    }
+
+    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
+    // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
+    // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
+    // for more information.
+
+    if (frameDuration < 0.011f) {
+        frameDuration = 0.100f;
+    }
+
+    CFRelease(cfFrameProperties);
+    return frameDuration;
+}
+
++ (UIImage *)sd_animatedGIFNamed:(NSString *)name {
+    CGFloat scale = [UIScreen mainScreen].scale;
+
+    if (scale > 1.0f) {
+        NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
+
+        NSData *data = [NSData dataWithContentsOfFile:retinaPath];
+
+        if (data) {
+            return [UIImage sd_animatedGIFWithData:data];
+        }
+
+        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
+
+        data = [NSData dataWithContentsOfFile:path];
+
+        if (data) {
+            return [UIImage sd_animatedGIFWithData:data];
+        }
+
+        return [UIImage imageNamed:name];
+    }
+    else {
+        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
+
+        NSData *data = [NSData dataWithContentsOfFile:path];
+
+        if (data) {
+            return [UIImage sd_animatedGIFWithData:data];
+        }
+
+        return [UIImage imageNamed:name];
+    }
+}
+
+- (UIImage *)sd_animatedImageByScalingAndCroppingToSize:(CGSize)size {
+    if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {
+        return self;
+    }
+
+    CGSize scaledSize = size;
+    CGPoint thumbnailPoint = CGPointZero;
+
+    CGFloat widthFactor = size.width / self.size.width;
+    CGFloat heightFactor = size.height / self.size.height;
+    CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;
+    scaledSize.width = self.size.width * scaleFactor;
+    scaledSize.height = self.size.height * scaleFactor;
+
+    if (widthFactor > heightFactor) {
+        thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;
+    }
+    else if (widthFactor < heightFactor) {
+        thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;
+    }
+
+    NSMutableArray *scaledImages = [NSMutableArray array];
+
+    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
+
+    for (UIImage *image in self.images) {
+        [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];
+        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
+
+        [scaledImages addObject:newImage];
+    }
+
+    UIGraphicsEndImageContext();
+
+    return [UIImage animatedImageWithImages:scaledImages duration:self.duration];
+}
+
+@end
diff --git a/SDWebImage/UIImage+MultiFormat.h b/SDWebImage/UIImage+MultiFormat.h
new file mode 100644
index 0000000..186ebc0
--- /dev/null
+++ b/SDWebImage/UIImage+MultiFormat.h
@@ -0,0 +1,15 @@
+//
+//  UIImage+MultiFormat.h
+//  SDWebImage
+//
+//  Created by Olivier Poitrey on 07/06/13.
+//  Copyright (c) 2013 Dailymotion. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface UIImage (MultiFormat)
+
++ (UIImage *)sd_imageWithData:(NSData *)data;
+
+@end
diff --git a/SDWebImage/UIImage+MultiFormat.m b/SDWebImage/UIImage+MultiFormat.m
new file mode 100644
index 0000000..5395280
--- /dev/null
+++ b/SDWebImage/UIImage+MultiFormat.m
@@ -0,0 +1,114 @@
+//
+//  UIImage+MultiFormat.m
+//  SDWebImage
+//
+//  Created by Olivier Poitrey on 07/06/13.
+//  Copyright (c) 2013 Dailymotion. All rights reserved.
+//
+
+#import "UIImage+MultiFormat.h"
+#import "UIImage+GIF.h"
+#import "NSData+ImageContentType.h"
+#import <ImageIO/ImageIO.h>
+
+#ifdef SD_WEBP
+#import "UIImage+WebP.h"
+#endif
+
+@implementation UIImage (MultiFormat)
+
++ (UIImage *)sd_imageWithData:(NSData *)data {
+    UIImage *image;
+    NSString *imageContentType = [NSData sd_contentTypeForImageData:data];
+    if ([imageContentType isEqualToString:@"image/gif"]) {
+        image = [UIImage sd_animatedGIFWithData:data];
+    }
+#ifdef SD_WEBP
+    else if ([imageContentType isEqualToString:@"image/webp"])
+    {
+        image = [UIImage sd_imageWithWebPData:data];
+    }
+#endif
+    else {
+        image = [[UIImage alloc] initWithData:data];
+        UIImageOrientation orientation = [self sd_imageOrientationFromImageData:data];
+        if (orientation != UIImageOrientationUp) {
+            image = [UIImage imageWithCGImage:image.CGImage
+                                        scale:image.scale
+                                  orientation:orientation];
+        }
+    }
+
+
+    return image;
+}
+
+
++(UIImageOrientation)sd_imageOrientationFromImageData:(NSData *)imageData {
+    UIImageOrientation result = UIImageOrientationUp;
+    CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)imageData, NULL);
+    if (imageSource) {
+        CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
+        if (properties) {
+            CFTypeRef val;
+            int exifOrientation;
+            val = CFDictionaryGetValue(properties, kCGImagePropertyOrientation);
+            if (val) {
+                CFNumberGetValue(val, kCFNumberIntType, &exifOrientation);
+                result = [self sd_exifOrientationToiOSOrientation:exifOrientation];
+            } // else - if it's not set it remains at up
+            CFRelease((CFTypeRef) properties);
+        } else {
+            //NSLog(@"NO PROPERTIES, FAIL");
+        }
+        CFRelease(imageSource);
+    }
+    return result;
+}
+
+#pragma mark EXIF orientation tag converter
+// Convert an EXIF image orientation to an iOS one.
+// reference see here: http://sylvana.net/jpegcrop/exif_orientation.html
++ (UIImageOrientation) sd_exifOrientationToiOSOrientation:(int)exifOrientation {
+    UIImageOrientation orientation = UIImageOrientationUp;
+    switch (exifOrientation) {
+        case 1:
+            orientation = UIImageOrientationUp;
+            break;
+
+        case 3:
+            orientation = UIImageOrientationDown;
+            break;
+
+        case 8:
+            orientation = UIImageOrientationLeft;
+            break;
+
+        case 6:
+            orientation = UIImageOrientationRight;
+            break;
+
+        case 2:
+            orientation = UIImageOrientationUpMirrored;
+            break;
+
+        case 4:
+            orientation = UIImageOrientationDownMirrored;
+            break;
+
+        case 5:
+            orientation = UIImageOrientationLeftMirrored;
+            break;
+
+        case 7:
+            orientation = UIImageOrientationRightMirrored;
+            break;
+        default:
+            break;
+    }
+    return orientation;
+}
+
+
+
+@end
diff --git a/SDWebImage/UIImageView+HighlightedWebCache.h b/SDWebImage/UIImageView+HighlightedWebCache.h
new file mode 100644
index 0000000..6b00366
--- /dev/null
+++ b/SDWebImage/UIImageView+HighlightedWebCache.h
@@ -0,0 +1,100 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <UIKit/UIKit.h>
+#import "SDWebImageCompat.h"
+#import "SDWebImageManager.h"
+
+/**
+ * Integrates SDWebImage async downloading and caching of remote images with UIImageView for highlighted state.
+ */
+@interface UIImageView (HighlightedWebCache)
+
+/**
+ * Set the imageView `highlightedImage` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url The url for the image.
+ */
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url;
+
+/**
+ * Set the imageView `highlightedImage` with an `url` and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url     The url for the image.
+ * @param options The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ */
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options;
+
+/**
+ * Set the imageView `highlightedImage` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `highlightedImage` with an `url` and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `highlightedImage` with an `url` and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param progressBlock  A block called while image is downloading
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Cancel the current download
+ */
+- (void)sd_cancelCurrentHighlightedImageLoad;
+
+@end
+
+
+@interface UIImageView (HighlightedWebCacheDeprecated)
+
+- (void)setHighlightedImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:`");
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:`");
+- (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:completed:`");
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:completed:`");
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setHighlightedImageWithURL:options:progress:completed:`");
+
+- (void)cancelCurrentHighlightedImageLoad __deprecated_msg("Use `sd_cancelCurrentHighlightedImageLoad`");
+
+@end
diff --git a/SDWebImage/UIImageView+HighlightedWebCache.m b/SDWebImage/UIImageView+HighlightedWebCache.m
new file mode 100644
index 0000000..ae73610
--- /dev/null
+++ b/SDWebImage/UIImageView+HighlightedWebCache.m
@@ -0,0 +1,107 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "UIImageView+HighlightedWebCache.h"
+#import "UIView+WebCacheOperation.h"
+
+#define UIImageViewHighlightedWebCacheOperationKey @"highlightedImage"
+
+@implementation UIImageView (HighlightedWebCache)
+
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url {
+    [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
+}
+
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
+    [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
+}
+
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:completedBlock];
+}
+
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:completedBlock];
+}
+
+- (void)sd_setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_cancelCurrentHighlightedImageLoad];
+
+    if (url) {
+        __weak UIImageView      *wself    = self;
+        id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+            if (!wself) return;
+            dispatch_main_sync_safe (^
+                                     {
+                                         if (!wself) return;
+                                         if (image) {
+                                             wself.highlightedImage = image;
+                                             [wself setNeedsLayout];
+                                         }
+                                         if (completedBlock && finished) {
+                                             completedBlock(image, error, cacheType, url);
+                                         }
+                                     });
+        }];
+        [self sd_setImageLoadOperation:operation forKey:UIImageViewHighlightedWebCacheOperationKey];
+    } else {
+        dispatch_main_async_safe(^{
+            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
+            if (completedBlock) {
+                completedBlock(nil, error, SDImageCacheTypeNone, url);
+            }
+        });
+    }
+}
+
+- (void)sd_cancelCurrentHighlightedImageLoad {
+    [self sd_cancelImageLoadOperationWithKey:UIImageViewHighlightedWebCacheOperationKey];
+}
+
+@end
+
+
+@implementation UIImageView (HighlightedWebCacheDeprecated)
+
+- (void)setHighlightedImageWithURL:(NSURL *)url {
+    [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:nil];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options {
+    [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:nil];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setHighlightedImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setHighlightedImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setHighlightedImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setHighlightedImageWithURL:url options:0 progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)cancelCurrentHighlightedImageLoad {
+    [self sd_cancelCurrentHighlightedImageLoad];
+}
+
+@end
diff --git a/SDWebImage/UIImageView+WebCache.h b/SDWebImage/UIImageView+WebCache.h
new file mode 100644
index 0000000..717d393
--- /dev/null
+++ b/SDWebImage/UIImageView+WebCache.h
@@ -0,0 +1,201 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "SDWebImageCompat.h"
+#import "SDWebImageManager.h"
+
+/**
+ * Integrates SDWebImage async downloading and caching of remote images with UIImageView.
+ *
+ * Usage with a UITableViewCell sub-class:
+ *
+ * @code
+
+#import <SDWebImage/UIImageView+WebCache.h>
+
+...
+
+- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
+{
+    static NSString *MyIdentifier = @"MyIdentifier";
+ 
+    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
+ 
+    if (cell == nil) {
+        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]
+                 autorelease];
+    }
+ 
+    // Here we use the provided sd_setImageWithURL: method to load the web image
+    // Ensure you use a placeholder image otherwise cells will be initialized with no image
+    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"]
+                      placeholderImage:[UIImage imageNamed:@"placeholder"]];
+ 
+    cell.textLabel.text = @"My Text";
+    return cell;
+}
+
+ * @endcode
+ */
+@interface UIImageView (WebCache)
+
+/**
+ * Get the current image URL.
+ *
+ * Note that because of the limitations of categories this property can get out of sync
+ * if you use sd_setImage: directly.
+ */
+- (NSURL *)sd_imageURL;
+
+/**
+ * Set the imageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url The url for the image.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url;
+
+/**
+ * Set the imageView `image` with an `url` and a placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @see sd_setImageWithURL:placeholderImage:options:
+ */
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url         The url for the image.
+ * @param placeholder The image to be set initially, until the image request finishes.
+ * @param options     The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
+
+/**
+ * Set the imageView `image` with an `url`.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url`, placeholder and custom options.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param progressBlock  A block called while image is downloading
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Set the imageView `image` with an `url` and a optionaly placeholder image.
+ *
+ * The download is asynchronous and cached.
+ *
+ * @param url            The url for the image.
+ * @param placeholder    The image to be set initially, until the image request finishes.
+ * @param options        The options to use when downloading the image. @see SDWebImageOptions for the possible values.
+ * @param progressBlock  A block called while image is downloading
+ * @param completedBlock A block called when operation has been completed. This block has no return value
+ *                       and takes the requested UIImage as first parameter. In case of error the image parameter
+ *                       is nil and the second parameter may contain an NSError. The third parameter is a Boolean
+ *                       indicating if the image was retrived from the local cache of from the network.
+ *                       The forth parameter is the original image url.
+ */
+- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
+
+/**
+ * Download an array of images and starts them in an animation loop
+ *
+ * @param arrayOfURLs An array of NSURL
+ */
+- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
+
+/**
+ * Cancel the current download
+ */
+- (void)sd_cancelCurrentImageLoad;
+
+- (void)sd_cancelCurrentAnimationImagesLoad;
+
+@end
+
+
+@interface UIImageView (WebCacheDeprecated)
+
+- (NSURL *)imageURL __deprecated_msg("Use `sd_imageURL`");
+
+- (void)setImageWithURL:(NSURL *)url __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:`");
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:`");
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options`");
+
+- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:completed:`");
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:completed:`");
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock __deprecated_msg("Method deprecated. Use `sd_setImageWithURL:placeholderImage:options:completed:`");
+- (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:`");
+
+- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs __deprecated_msg("Use `sd_setAnimationImagesWithURLs:`");
+
+- (void)cancelCurrentArrayLoad __deprecated_msg("Use `sd_cancelCurrentAnimationImagesLoad`");
+
+- (void)cancelCurrentImageLoad __deprecated_msg("Use `sd_cancelCurrentImageLoad`");
+
+@end
diff --git a/SDWebImage/UIImageView+WebCache.m b/SDWebImage/UIImageView+WebCache.m
new file mode 100644
index 0000000..51663dd
--- /dev/null
+++ b/SDWebImage/UIImageView+WebCache.m
@@ -0,0 +1,195 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "UIImageView+WebCache.h"
+#import "objc/runtime.h"
+#import "UIView+WebCacheOperation.h"
+
+static char imageURLKey;
+
+@implementation UIImageView (WebCache)
+
+- (void)sd_setImageWithURL:(NSURL *)url {
+    [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:completedBlock];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:completedBlock];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:completedBlock];
+}
+
+- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
+    [self sd_cancelCurrentImageLoad];
+    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+
+    if (!(options & SDWebImageDelayPlaceholder)) {
+        self.image = placeholder;
+    }
+    
+    if (url) {
+        __weak UIImageView *wself = self;
+        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+            if (!wself) return;
+            dispatch_main_sync_safe(^{
+                if (!wself) return;
+                if (image) {
+                    wself.image = image;
+                    [wself setNeedsLayout];
+                } else {
+                    if ((options & SDWebImageDelayPlaceholder)) {
+                        wself.image = placeholder;
+                        [wself setNeedsLayout];
+                    }
+                }
+                if (completedBlock && finished) {
+                    completedBlock(image, error, cacheType, url);
+                }
+            });
+        }];
+        [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
+    } else {
+        dispatch_main_async_safe(^{
+            NSError *error = [NSError errorWithDomain:@"SDWebImageErrorDomain" code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
+            if (completedBlock) {
+                completedBlock(nil, error, SDImageCacheTypeNone, url);
+            }
+        });
+    }
+}
+
+- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
+    NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
+    UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
+    
+    [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock];    
+}
+
+- (NSURL *)sd_imageURL {
+    return objc_getAssociatedObject(self, &imageURLKey);
+}
+
+- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
+    [self sd_cancelCurrentAnimationImagesLoad];
+    __weak UIImageView *wself = self;
+
+    NSMutableArray *operationsArray = [[NSMutableArray alloc] init];
+
+    for (NSURL *logoImageURL in arrayOfURLs) {
+        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
+            if (!wself) return;
+            dispatch_main_sync_safe(^{
+                __strong UIImageView *sself = wself;
+                [sself stopAnimating];
+                if (sself && image) {
+                    NSMutableArray *currentImages = [[sself animationImages] mutableCopy];
+                    if (!currentImages) {
+                        currentImages = [[NSMutableArray alloc] init];
+                    }
+                    [currentImages addObject:image];
+
+                    sself.animationImages = currentImages;
+                    [sself setNeedsLayout];
+                }
+                [sself startAnimating];
+            });
+        }];
+        [operationsArray addObject:operation];
+    }
+
+    [self sd_setImageLoadOperation:[NSArray arrayWithArray:operationsArray] forKey:@"UIImageViewAnimationImages"];
+}
+
+- (void)sd_cancelCurrentImageLoad {
+    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
+}
+
+- (void)sd_cancelCurrentAnimationImagesLoad {
+    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
+}
+
+@end
+
+
+@implementation UIImageView (WebCacheDeprecated)
+
+- (NSURL *)imageURL {
+    return [self sd_imageURL];
+}
+
+- (void)setImageWithURL:(NSURL *)url {
+    [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:nil];
+}
+
+- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:nil options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock {
+    [self sd_setImageWithURL:url placeholderImage:placeholder options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
+        if (completedBlock) {
+            completedBlock(image, error, cacheType);
+        }
+    }];
+}
+
+- (void)cancelCurrentArrayLoad {
+    [self sd_cancelCurrentAnimationImagesLoad];
+}
+
+- (void)cancelCurrentImageLoad {
+    [self sd_cancelCurrentImageLoad];
+}
+
+- (void)setAnimationImagesWithURLs:(NSArray *)arrayOfURLs {
+    [self sd_setAnimationImagesWithURLs:arrayOfURLs];
+}
+
+@end
diff --git a/SDWebImage/UIView+WebCacheOperation.h b/SDWebImage/UIView+WebCacheOperation.h
new file mode 100644
index 0000000..6719036
--- /dev/null
+++ b/SDWebImage/UIView+WebCacheOperation.h
@@ -0,0 +1,36 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import <UIKit/UIKit.h>
+#import "SDWebImageManager.h"
+
+@interface UIView (WebCacheOperation)
+
+/**
+ *  Set the image load operation (storage in a UIView based dictionary)
+ *
+ *  @param operation the operation
+ *  @param key       key for storing the operation
+ */
+- (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key;
+
+/**
+ *  Cancel all operations for the current UIView and key
+ *
+ *  @param key key for identifying the operations
+ */
+- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key;
+
+/**
+ *  Just remove the operations corresponding to the current UIView and key without cancelling them
+ *
+ *  @param key key for identifying the operations
+ */
+- (void)sd_removeImageLoadOperationWithKey:(NSString *)key;
+
+@end
diff --git a/SDWebImage/UIView+WebCacheOperation.m b/SDWebImage/UIView+WebCacheOperation.m
new file mode 100644
index 0000000..9219478
--- /dev/null
+++ b/SDWebImage/UIView+WebCacheOperation.m
@@ -0,0 +1,55 @@
+/*
+ * This file is part of the SDWebImage package.
+ * (c) Olivier Poitrey <rs@dailymotion.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+#import "UIView+WebCacheOperation.h"
+#import "objc/runtime.h"
+
+static char loadOperationKey;
+
+@implementation UIView (WebCacheOperation)
+
+- (NSMutableDictionary *)operationDictionary {
+    NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
+    if (operations) {
+        return operations;
+    }
+    operations = [NSMutableDictionary dictionary];
+    objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+    return operations;
+}
+
+- (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key {
+    [self sd_cancelImageLoadOperationWithKey:key];
+    NSMutableDictionary *operationDictionary = [self operationDictionary];
+    [operationDictionary setObject:operation forKey:key];
+}
+
+- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
+    // Cancel in progress downloader from queue
+    NSMutableDictionary *operationDictionary = [self operationDictionary];
+    id operations = [operationDictionary objectForKey:key];
+    if (operations) {
+        if ([operations isKindOfClass:[NSArray class]]) {
+            for (id <SDWebImageOperation> operation in operations) {
+                if (operation) {
+                    [operation cancel];
+                }
+            }
+        } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
+            [(id<SDWebImageOperation>) operations cancel];
+        }
+        [operationDictionary removeObjectForKey:key];
+    }
+}
+
+- (void)sd_removeImageLoadOperationWithKey:(NSString *)key {
+    NSMutableDictionary *operationDictionary = [self operationDictionary];
+    [operationDictionary removeObjectForKey:key];
+}
+
+@end