Asynchronous image downloader with cache support as a UIImageView category
Go to file
Bogdan Poplauschi 123f2fd2e6 Updated docs - tried to cleanup the readme, reorder based on other great projects examples and include the diagram 2016-05-10 08:39:46 +03:00
Examples Added the WebP files to the WebImage.framework target. Removed some old hack to define empty WebP methods (see #416), will re-add it if needed, right now it prevents the dynamic framework to build. 2016-05-08 22:41:33 +03:00
SDWebImage Added the WebP files to the WebImage.framework target. Removed some old hack to define empty WebP methods (see #416), will re-add it if needed, right now it prevents the dynamic framework to build. 2016-05-08 22:41:33 +03:00
SDWebImage.xcodeproj Schemes update (naming) 2016-05-10 08:37:12 +03:00
SDWebImage.xcworkspace Renamed the schemes for consistency, dynamic frameworks are named SDWebImage instead of WebImage. Updated the Tests Podfile + project. Renamed the WebImage.h to SDWebImage.h to match the framework naming 2016-05-08 22:59:32 +03:00
Tests Added the missing Tests scheme 2016-05-08 23:14:48 +03:00
Vendors Bumped the libwebp reference to 0.4.4 2016-01-08 16:34:18 +02:00
WebImage Renamed the schemes for consistency, dynamic frameworks are named SDWebImage instead of WebImage. Updated the Tests Podfile + project. Renamed the WebImage.h to SDWebImage.h to match the framework naming 2016-05-08 22:59:32 +03:00
.gitattributes Added 1st version of design (StarUML) 2016-05-08 23:58:26 +03:00
.gitignore Updated .gitignore 2015-10-25 20:44:35 +02:00
.gitmodules Update .gitmodules 2015-12-07 10:57:02 +08:00
.travis.yml The tests target should also use xcpretty 2016-05-08 23:41:31 +03:00
CHANGELOG.md Updated the changelog 2016-05-08 19:49:06 +03:00
LICENSE Also update copyright year 2016-02-17 20:18:49 +09:00
ManualInstallation.md Updated docs - tried to cleanup the readme, reorder based on other great projects examples and include the diagram 2016-05-10 08:39:46 +03:00
README.md Updated docs - tried to cleanup the readme, reorder based on other great projects examples and include the diagram 2016-05-10 08:39:46 +03:00
SDWebImage.mdj Updated the diagrams 2016-05-10 08:36:50 +03:00
SDWebImage.podspec Bumped version to 3.7.6 2016-05-08 19:32:10 +03:00
SDWebImageClassDiagram.png Updated docs - tried to cleanup the readme, reorder based on other great projects examples and include the diagram 2016-05-10 08:39:46 +03:00

README.md

SDWebImage

Build Status Pod Version Pod Platform Pod License Dependency Status Reference Status Carthage compatible

This library provides an async image downloader with cache support. For convenience, we added categories for some UIControl elements like UIImageView.

Features

  • Categories for UIImageView, UIButton, MKAnnotationView adding web image and cache management
  • An asynchronous image downloader
  • An asynchronous memory + disk image caching with automatic cache expiration handling
  • 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

Supported Image Formats

  • Image formats supported by UIImage (JPEG, PNG, ...), including GIF
  • WebP format (use the WebP subspec)

Requirements

  • iOS 5.1.1+ / tvOS 9.0+
  • Xcode 7.1+

Backwards compatibility

Getting Started

Who Uses It

Installation

How To Use

Using UIImageView+WebCache category with UITableView

Just import the UIImageView+WebCache.h header, and call the sd_setImageWithURL:placeholderImage: method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be handled for you, from async downloads to caching management.

#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 sd_setImageWithURL: method to load the web image
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}
import SDWebImage
...
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    static let myIdentifier = "MyIdentifier"
    let cell = tableView.dequeueReusableCellWithIdentifier(myIdentifier, forIndexPath: indexPath) as UITableViewCell

    cell.imageView.sd_setImageWithURL(imageUrl, placeholderImage:placeholderImage)
    return cell

Using blocks

With blocks, you can be notified about the image download progress and whenever the image retrieval has completed with success or not:

// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                  placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                         completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                ... 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:

SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager loadImageWithURL:imageURL
                  options:0
                 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                        // progression tracking code
                 }
                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    if (image) {
                        // do something with image
                    }
                 }];

Using Asynchronous Image Downloader Independently

It's also possible to use the async image downloader independently:

SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader 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 async 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.

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:

[[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:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) {
        url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
        return [url absoluteString];
    };

    // Your app init code...
    return YES;
}

Common Problems

Using dynamic image size with UITableViewCell

UITableView determines 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/

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:

[imageView sd_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 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 section for more details.

Podfile

platform :ios, '6.1'
pod 'SDWebImage', '~>3.7'

If you are using Swift, be sure to add use_frameworks! and set your target to iOS 8+:

platform :ios, '8.0'
use_frameworks!

Subspecs

There are 3 subspecs available now: Core, MapKit and WebP (this means you can install only some of the SDWebImage modules. By default, you get just Core, so if you need WebP, you need to specify it).

Podfile example:

pod 'SDWebImage/WebP'

Installation with Carthage (iOS 8+)

Carthage is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods.

To install with carthage, follow the instruction on Carthage

Cartfile

github "rs/SDWebImage"

Installation by cloning the repository

Import headers in your source files

In the source files where you need to use the library, import the header file:

#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.

Architecture