1Web Image
2=========
3[![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/SDWebImage)
4[![Pod Version](http://img.shields.io/cocoapods/v/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
5[![Pod Platform](http://img.shields.io/cocoapods/p/SDWebImage.svg?style=flat)](http://cocoadocs.org/docsets/SDWebImage/)
6[![Pod License](http://img.shields.io/cocoapods/l/SDWebImage.svg?style=flat)](https://www.apache.org/licenses/LICENSE-2.0.html)
7
8This library provides a category for UIImageView with support for remote images coming from the web.
9
10It provides:
11
12- An UIImageView category adding web image and cache management to the Cocoa Touch framework
13- An asynchronous image downloader
14- An asynchronous memory + disk image caching with automatic cache expiration handling
15- Animated GIF support
16- WebP format support
17- A background image decompression
18- A guarantee that the same URL won't be downloaded several times
19- A guarantee that bogus URLs won't be retried again and again
20- A guarantee that main thread will never be blocked
21- Performances!
22- Use GCD and ARC
23- Arm64 support
24
25NOTE: The version 3.0 of SDWebImage isn't fully backward compatible with 2.0 and requires iOS 5.1.1
26minimum 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).
27
28[How is SDWebImage better than X?](https://github.com/rs/SDWebImage/wiki/How-is-SDWebImage-better-than-X%3F)
29
30Who Use It
31----------
32
33Find out [who uses SDWebImage](https://github.com/rs/SDWebImage/wiki/Who-Uses-SDWebImage) and add your app to the list.
34
35How To Use
36----------
37
38API documentation is available at [http://hackemist.com/SDWebImage/doc/](http://hackemist.com/SDWebImage/doc/)
39
40### Using UIImageView+WebCache category with UITableView
41
42Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage:
43method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be
44handled for you, from async downloads to caching management.
45
46```objective-c
47#import <SDWebImage/UIImageView+WebCache.h>
48
49...
50
51- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
52{
53    static NSString *MyIdentifier = @"MyIdentifier";
54
55    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
56
57    if (cell == nil)
58    {
59        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
60                                       reuseIdentifier:MyIdentifier] autorelease];
61    }
62
63    // Here we use the new provided setImageWithURL: method to load the web image
64    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
65                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
66
67    cell.textLabel.text = @"My Text";
68    return cell;
69}
70```
71
72### Using blocks
73
74With blocks, you can be notified about the image download progress and whenever the image retrival
75has completed with success or not:
76
77```objective-c
78// Here we use the new provided setImageWithURL: method to load the web image
79[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
80               placeholderImage:[UIImage imageNamed:@"placeholder.png"]
81                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];
82```
83
84Note: neither your success nor failure block will be call if your image request is canceled before completion.
85
86### Using SDWebImageManager
87
88The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the
89asynchronous downloader with the image cache store. You can use this class directly to benefit
90from web image downloading with caching in another context than a UIView (ie: with Cocoa).
91
92Here is a simple example of how to use SDWebImageManager:
93
94```objective-c
95SDWebImageManager *manager = [SDWebImageManager sharedManager];
96[manager downloadWithURL:imageURL
97                 options:0
98                 progress:^(NSInteger receivedSize, NSInteger expectedSize)
99                 {
100                     // progression tracking code
101                 }
102                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
103                 {
104                     if (image)
105                     {
106                         // do something with image
107                     }
108                 }];
109```
110
111### Using Asynchronous Image Downloader Independently
112
113It's also possible to use the async image downloader independently:
114
115```objective-c
116[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
117                                                    options:0
118                                                   progress:^(NSInteger receivedSize, NSInteger expectedSize)
119                                                   {
120                                                       // progression tracking code
121                                                   }
122                                                   completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
123                                                   {
124                                                       if (image && finished)
125                                                       {
126                                                           // do something with image
127                                                       }
128                                                   }];
129```
130
131### Using Asynchronous Image Caching Independently
132
133It is also possible to use the aync based image cache store independently. SDImageCache
134maintains a memory cache and an optional disk cache. Disk cache write operations are performed
135asynchronous so it doesn't add unnecessary latency to the UI.
136
137The SDImageCache class provides a singleton instance for convenience but you can create your own
138instance if you want to create separated cache namespace.
139
140To lookup the cache, you use the `queryDiskCacheForKey:done:` method. If the method returns nil, it means the cache
141doesn't currently own the image. You are thus responsible for generating and caching it. The cache
142key is an application unique identifier for the image to cache. It is generally the absolute URL of
143the image.
144
145```objective-c
146SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
147[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
148{
149    // image is not nil if image was found
150}];
151```
152
153By default SDImageCache will lookup the disk cache if an image can't be found in the memory cache.
154You can prevent this from happening by calling the alternative method `imageFromMemoryCacheForKey:`.
155
156To store an image into the cache, you use the storeImage:forKey: method:
157
158```objective-c
159[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
160```
161
162By default, the image will be stored in memory cache as well as on disk cache (asynchronously). If
163you want only the memory cache, use the alternative method storeImage:forKey:toDisk: with a negative
164third argument.
165
166### Using cache key filter
167
168Sometime, you may not want to use the image URL as cache key because part of the URL is dynamic
169(i.e.: for access control purpose). SDWebImageManager provides a way to set a cache key filter that
170takes the NSURL as input, and output a cache key NSString.
171
172The following example sets a filter in the application delegate that will remove any query-string from
173the URL before to use it as a cache key:
174
175```objective-c
176- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
177{
178    SDWebImageManager.sharedManager.cacheKeyFilter:^(NSURL *url)
179    {
180        url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
181        return [url absoluteString];
182    };
183
184    // Your app init code...
185    return YES;
186}
187```
188
189
190Common Problems
191---------------
192
193### Using dynamic image size with UITableViewCell
194
195UITableView determins the size of the image by the first image set for a cell. If your remote images
196don't have the same size as your placeholder image, you may experience strange anamorphic scaling issue.
197The following article gives a way to workaround this issue:
198
199[http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/](http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/)
200
201
202### Handle image refresh
203
204SDWebImage 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.
205
206If 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:
207
208``` objective-c
209[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
210          placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
211                   options:SDWebImageRefreshCached];
212```
213
214### Add a progress indicator
215
216See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
217
218Installation
219------------
220
221There are three ways to use SDWebImage in your project:
222- using Cocoapods
223- copying all the files into your project
224- importing the project as a static library
225
226### Installation with CocoaPods
227
228[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.
229
230#### Podfile
231```
232platform :ios, '6.1'
233pod 'SDWebImage', '~>3.6'
234```
235
236### Add the SDWebImage project to your project
237
238- Download and unzip the last version of the framework from the [download page](https://github.com/rs/SDWebImage/releases)
239- Right-click on the project navigator and select "Add Files to "Your Project":
240- In the dialog, select SDWebImage.framework:
241- Check the "Copy items into destination group's folder (if needed)" checkbox
242
243### Add dependencies
244
245- In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block:
246- Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature:
247
248### Add Linker Flag
249
250Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag:
251
252![Other Linker Flags](http://dl.dropbox.com/u/123346/SDWebImage/10_other_linker_flags.jpg)
253
254Alternatively, if this causes compilation problems with frameworks that extend optional libraries, such as Parse,  RestKit or opencv2, instead of the -ObjC flag use:
255
256```
257-force_load SDWebImage.framework/Versions/Current/SDWebImage
258```
259
260### Import headers in your source files
261
262In the source files where you need to use the library, import the header file:
263
264```objective-c
265#import <SDWebImage/UIImageView+WebCache.h>
266```
267
268### Build Project
269
270At this point your workspace should build without error. If you are having problem, post to the Issue and the
271community can help you solve it.
272
273Future Enhancements
274-------------------
275
276- LRU memory cache cleanup instead of reset on memory warning
277
278## Licenses
279
280All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE).
281