Quantcast
Channel: iOS Development Tips & Tricks by BiOM » image
Viewing all articles
Browse latest Browse all 8

SDWebImage for iOS

$
0
0

UIImageView category adding suppport for remote images coming from the web asynchronously with caching.

Full\

GitHub

How To Use

API documentation is available at 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.

  1. #import <SDWebImage/UIImageView+WebCache.h>
  2.  
  3. ...
  4.  
  5. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  6. {
  7.     static NSString *MyIdentifier = @"MyIdentifier";
  8.  
  9.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
  10.  
  11.     if (cell == nil)
  12.     {
  13.         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
  14.                                        reuseIdentifier:MyIdentifier] autorelease];
  15.     }
  16.  
  17.     // Here we use the new provided setImageWithURL: method to load the web image
  18.     [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
  19.                    placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
  20.  
  21.     cell.textLabel.text = @"My Text";
  22.     return cell;
  23. }
#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:

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

  1. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  2. [manager downloadWithURL:imageURL
  3.                  options:0
  4.                  progress:^(NSUInteger receivedSize, long long expectedSize)
  5.                  {
  6.                      // progression tracking code
  7.                  }
  8.                  completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
  9.                  {
  10.                      if (image)
  11.                      {
  12.                          // do something with image
  13.                      }
  14.                  }];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
                 options:0
                 progress:^(NSUInteger receivedSize, long long expectedSize)
                 {
                     // progression tracking code
                 }
                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
                 {
                     if (image)
                     {
                         // do something with image
                     }
                 }];

Using Asynchronous Image Downloader Independently

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

[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
                                                    options:0
                                                   progress:^(NSUInteger receivedSize, long long expectedSize)
                                                   {
                                                       // progression tracking code
                                                   }
                                                   completed:^(UIImage *image, 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 imageForKey: 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.

  1. SDImageCache *imageCache = [SDImageCache.alloc initWithNamespace:@"myNamespace"];
  2. [imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
  3. {
  4.     // image is not nil if image was found
  5. }];
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:

  1. [[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
[[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:

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3.     SDWebImageManager.sharedManager.cacheKeyFilter:^(NSURL *url)
  4.     {
  5.         url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
  6.         return [url absoluteString];
  7.     };
  8.  
  9.     // Your app init code...
  10.     return YES;
  11. }
- (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;
}


Viewing all articles
Browse latest Browse all 8

Trending Articles