SDWebImage 的常用方法使用

原创 2015年11月20日 20:45:54

API documentation is available at CocoaDocs - SDWebImage

UITableView中使用 UIImageView+WebCache category

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.

#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;
}

使用 blocks

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

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

使用 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 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
                     }
                 }];

使用 Asynchronous Image Downloader Independently

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

[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
                                                       }
                                                   }];

使用 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.

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 methodimageFromMemoryCacheForKey:.

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.

使用 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;
}

常见问题

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/

图片更新

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 setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
          placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
                   options:SDWebImageRefreshCached];

添加加载进度条

See this category: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage

版权声明:VIC

SDWebImage源码解读,分解流程,超细注解,进阶必备

非常用心的个人分析和注解,看完绝对让你有所收获 缓存的核心就是NSCache和NSFileManager的二级操作 下载的核心其实就是利用NSURLSession来在自定义的NSOperation对象...
  • Deft_MKJing
  • Deft_MKJing
  • 2016年10月23日 16:41
  • 3025

SDWebImage 原理及使用

SDWebImage托管在github上。https://github.com/rs/SDWebImage 这个类库提供一个UIImageView类别以支持加载来自网络的远程图片。具有缓存管理、...
  • huang2009303513
  • huang2009303513
  • 2014年11月21日 22:54
  • 18273

使用SDWebimage加载高清大图遇到内存警告的问题

在github看到SDWebImage的介绍,后面说到: Future Enhancements LRU memory cache cleanup instead of reset on ...
  • CaryG
  • CaryG
  • 2016年10月24日 12:09
  • 1689

SDWebImage常用方法

//常用方法一 - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder; //例如: [cel...
  • SKYHIKu
  • SKYHIKu
  • 2017年03月21日 14:38
  • 208

SDWebImage的常用缓存方法

一步,下载SDWebImage,导入工程。github托管地址https://github.com/rs/SDWebImage 第二步,在需要的地方导入头文件 #import "UIIma...
  • strong90
  • strong90
  • 2015年12月29日 21:17
  • 136

SDWebImage使用方法

SDWebImage,
  • Flyingasnail
  • Flyingasnail
  • 2015年09月05日 17:44
  • 248

SDWebImage的一个很好的使用方法

在网站上看到大牛们在分析SDWebImage,所以就借鉴了自己觉得不错的地方,大家可以瞅一眼。 SDWebImage作为目前最受欢迎的图片下载第三方框架,使用率很高。本文将通过例子分析如何合...
  • wujakf
  • wujakf
  • 2016年12月08日 17:46
  • 213

SDWebImage使用方法

SDWebImage作为目前最受欢迎的图片下载第三方框架,使用率很高。但是你真的会用吗?本文接下来将通过例子分析如何合理使用SDWebImage。 使用场景:自定义的UITableViewCel...
  • wc455287693
  • wc455287693
  • 2016年05月03日 15:11
  • 273

SDWebImage 更新 简单使用方法

最新版本下载地址 :https://github.com/rs/SDWebImage
  • aiyun0628
  • aiyun0628
  • 2014年09月26日 21:32
  • 1007

SDWebImage常用函数

"加载GIF图"- (void)loadGIF { NSURL *URL; // 加载网络gif图 URL = [NSURL URLWithString:@"http://pho...
  • sinat_20559947
  • sinat_20559947
  • 2016年09月21日 17:15
  • 189
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:SDWebImage 的常用方法使用
举报原因:
原因补充:

(最多只允许输入30个字)