异步加载图片的库SDWebImage

转自:https://github.com/rs/SDWebImage


How To Use It

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.

#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

If your project's deployement target is set to iOS 4+, you may want to use the success/failure blocks to be notified when image have been retrieved from cache.

// 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"]
                        success:^(UIImage *image) {... success code here ...}
                        failure:^(NSError *error) {... failure 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 downloadWithURL:imageURL
                delegate:self
                 options:0
                 success:^(UIImage *image)
                 {
                     // do something with image
                 }
                 failure:nil];

Using Asynchronous Image Downloader Independently

It is possible to use the async image downloader independently. You just have to create an instance of SDWebImageDownloader using its convenience constructor downloaderWithURL:delegate:.

downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];

The download will start immediately and the imageDownloader:didFinishWithImage: method from the SDWebImageDownloaderDelegate protocol will be called as soon as the download of image is completed.

Using Asynchronous Image Caching Independently

It is also possible to use the NSOperation 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.

UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:myCacheKey];

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 imageFromKey:fromDisk: with a negative second argument.

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] setCacheKeyFilter:^(NSURL *url)
    {
        url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
        return [url absoluteString];
    }];

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

Common Problems

No image appear when using UITableViewCell

If choose to use a default cell template provided by UITableViewCell with SDWebImage, ensure you are providing a placeholder image, otherwise the cell will be initialized with no image.

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/

Automatic Reference Counting (ARC)

You can use either style in your Cocoa project. SDWebImage Will figure out which you are using at compile time and do the right thing.

Installation

There are two ways to use this in your project: copy all the files into your project, or import the project as a static library.

Add the SDWebImage project to your project

Right-click on the project navigator and select "Add Files to "Your Project":

Add Library Project

In the dialog, select SDWebImage.xcodeproj:

Add Library Project Dialog

After you’ve added the subproject, it’ll appear below the main project in Xcode’s Navigator tree:

Library Added

You may want to add the SDWebImage directory in your project source tree as a submodule before adding it to your project.

Add build target dependencies

In you application project app’s target settings, find the "Build Phases" section and open the "Target Dependencies" block:

Add Target Dependencies

Click the "+" button and select "SDWebImage ARC" (you may choose the non ARC target if you want to support iOS <3):

Add Target Dependencies Dialog

Open the "Link Binary With Libraries" block:

Add Library Link

Click the "+" button and select "libSDWebImageARC.a" library (use non ARC version if you chose non ARC version in the previous step):

Add Library Link Dialog

Click the "+" button again and select "MapKit.framework", this is used by MKAnnotationView+WebCache category:

Add ImageIO Framework

Click the "+" button again and select the "ImageIO.framework", this is needed by the progressive download feature:

Add MapKit Framework

Add headers

Open the "Build Settings" tab, locate the "Other Linker Flags" setting and add the "-ObjC" flag:

Other Linker Flags

Locate "Header Search Paths" (and not "User Header Search Paths") and add two settings: ”$(TARGET_BUILD_DIR)/usr/local/lib/include” and ”$(OBJROOT)/UninstalledProducts/include”. Make sure to include the quotes here:

User Header Search Paths

Import headers in your source files

In the source files where you need to use the library, use #import <SDWebImage/HeaderFileName.h>:

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

Fixing indexing

If you have problem with auto-completion of SDWebImage methods, you may have to copy the header files in your project.

Future Enhancements

  • LRU memory cache cleanup instead of reset on memory warning

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值