SDWebImage基本使用

来源:互联网 发布:pos机软件 编辑:程序博客网 时间:2024/05/22 10:54
<span style="font-size:14px;">- (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;}</span>

### Using UIImageView+WebCache category with UITableView

在tableView中使用UIImageView+WebCache类目


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.

引入UIImageView+WebCache.h头文件,并且在tableView:cellForRowAtIndexPath: UITableViewDataSource中调用setImageWithURL:placeholderImage:方法。一些都已经设置好了,异步下载并作缓存处理。

-------------------------------------------------------------------------------------------------

<span style="font-size:14px;">```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 ...}];</span>

### Using blocks


With blocks, you can be notified about the image download progress and whenever the image retrival

has completed with success or not:

使用block,你可以知道图片下载的进程和图片什么时候成功下载。

Note: neither your success nor failure block will be call if your image request is canceled before completion.

注意:如果你的图片请求在完成之前被取消,那么success或者failure代码块都不会执行。

-------------------------------------------------------------------------------------------------

<span style="font-size:14px;">```objective-cSDWebImageManager *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                     }                 }];```</span>

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

SDWebImageManager是UIImageView+WebCache之后的一个类。它把异步下载和图片缓存联系在一起。你可以直接使用这个类来进行网络图片的下载和缓存这种情形而非加载到一个UIView对象上。

Here is a simple example of how to use SDWebImageManager:

以上是一个举例。

-------------------------------------------------------------------------------------------------

<span style="font-size:14px;">```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                                                       }                                                   }];```</span>

### Using Asynchronous Image Downloader Independently

独立地使用图片异步加载类

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

也有可能你需要独立地使用图片异步下载这个类

-------------------------------------------------------------------------------------------------


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

也有可能你需要独立地使用异步的图片缓存类。SDImageCache有内存缓存和选择性的磁盘缓存。磁盘缓存的写入操作是异步执行的所以它不会给界面带来不必要的影响。

The SDImageCache class provides a singleton instance for convenience but you can create your own

instance if you want to create separated cache namespace.

为了方便,SDImageCache类提供了一个单例对象,但是你如果想创建一个分开的缓存空间你可以创建你自己的实例。

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.


如果要查看缓存,你可以调用queryDiskCacheForKey:done:这个方法。如果这个方法返回nil,这意味着缓存里面现在没有这张图片。因此你需要产生并缓存这个图片。cache key是应用中为了缓存图片而设置的唯一标识。它通常是这个图片的绝对地址。

```objective-cSDImageCache *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:`.

默认的,SDImageCache如果没有在内存缓存中找到一张图片,它会在磁盘缓存中查找。你可以调用一个备选方法

To store an image into the cache, you use the storeImage:forKey: method:imageFromMemoryCacheForKey:来阻止这件事的发生。

To store an image into the cache, you use the storeImage:forKey: method:


为了将一张图片缓存起来,你可以使用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.

默认的,图片会被存储在内存中和磁盘中(异步的)。如果你只想要内存缓存,使用可选方法storeImage:forKey:toDisk: 

-------------------------------------------------------------------------------------------------

### Using cache key filter

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

有时你可能不想使用图片的URL作为缓存key因为URL的一部分是动态的(例如:为了控制对图片的获取)。SDWebImageManager提供了一个方法通过设置缓存钥匙过滤将NSURL输入,然后产生一个缓存钥匙字符串。

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:

下面的例子在应用代理中设置了过滤,它将在使用其作为缓存钥匙之前从URL中移除所有的查询字符串。

```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];        return [url absoluteString];    };    // Your app init code...    return YES;}```

-------------------------------------------------------------------------------------------------

Common Problems

常见问题

---------------


### Using dynamic image size with UITableViewCell

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:

UITableview根据第一个设置给cell的图片来决定图片的大小。如果你请求的图片和你的占位图的大小不一致,你可能会遇到图片比例失真的问题。下面这两篇文章给你提供了解决问题的办法。

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

SDWebImage默认有着积极的缓存行为。它忽略了所有的http服务器返回的缓存控制请求头中的数据并且没有时间限制的将返回的图片进行缓存。它需要你的图片地址是稳定的并且指向一张不变的图片。如果指向的图片碰巧改变了,URL的一部分也要响应的改变。

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:

如果你不控制你正在使用的图片服务器,当图片改变时你可能不能改变URL。这种情况就类似于facebook中的头像地址。在这种情况下,你可以使用SDWebImageRefreshCached标签。这会稍微降低性能但是将会遵循http缓存控制请求头。

``` objective-c[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]          placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]                   options:SDWebImageRefreshCached];```



-------------------------------------------------------------------------------------------------




0 0
原创粉丝点击