iOS网络图片缓存SDWebImage
Web image(网络图像)
该库提供了一个支持来自Web的远程图像的UIImageView类别
它提供了:
- 添加网络图像和缓存管理到Cocoa Touch framework的UIImageView类别
- 异步图像下载
- An asynchronous memory + disk image caching with automatic cache expiration handling
- 支持GIF动画
- 支持WebP格式
- 后台图像解压
- 保证相同的url不会下载多次
- 保证伪造的URL不会尝试一遍又一遍的下载
- 保证主线程永远不会被阻塞
- Performances!
- 使用GCD和ARC
注意:SDWebImage 3.0不向后兼容2.0并且最低需要iOS 5.0 的版本。如果你的iOS版本低于5.0,请使用2.0版本。
如何使用
API 文档地址 http://hackemist.com/SDWebImage/doc/。
Using UIImageView+WebCache category with UITableView
仅需引入 UIImageView+WebCache.h 头文件,在UITableViewDataSource的方法tableView:cellForRowAtIndexPath:中调用setImageWithURL:placeholderImage:方法。从异步下载到缓存管理,一切都会为你处理。
#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
// 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 ...}];
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 *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 } }];
[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL options:0 progress:^(NSUInteger receivedSize, long long expectedSize) { // progression tracking code } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { if (image && finished) { // do something with image } }];
SDImageCache *imageCache = [SDImageCache.alloc initWithNamespace:@"myNamespace"]; [imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) { // image is not nil if image was found }];
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
Using cache key filter
有时你也许不想使用图像URL作为缓存键,因为URL可能是动态的(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中删除任何查询字符串(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] autorelease]; return [url absoluteString]; }; // Your app init code... return YES; }
Using dynamic image size with UITableViewCell
UITableView通过第一个单元格设置的图像决定图像的尺寸。如果您的远程图像没有图像占位符的大小相同,您可能会遇到奇怪的变形缩放问题。下面的文章给出了一个方法来解决这个问题:
http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/
Handle image refresh(控制图像刷新)
默认情况下,SDWebImage确实非常积极的缓存。它忽略了所有类型的通过HTTP服务器返回的缓存控制头,并
如果你不控制你的图像服务器,当它的内容更新时你不能改变它的url。Facebook头像就是这种情况的例子。在这种情况下,你可以使用SDWebImageRefreshCached的标志。这将稍微降低性能,但将会考虑到HTTP缓存控制头:
[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"] placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"] options:SDWebImageRefreshCached];
Add a progress indicator(添加进度指示)
查看这个类别: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
Installation(安装)
Add the SDWebImage project to your project
- Download and unzip the last version of the framework from the download page
- Right-click on the project navigator and select "Add Files to "Your Project":
- In the dialog, select SDWebImage.framework:
- Check the "Copy items into destination group‘s folder (if needed)" checkbox
Add dependencies(添加依赖性)
- In you application project app’s target settings, find the "Build Phases" section and open the "Link Binary With Libraries" block:
- Click the "+" button again and select the "ImageIO.framework"(还缺一个“MapKit.framework”,readme中没提到), this is needed by the progressive download feature:
Add Linker Flag(添加链接标志)
Open the "Build Settings" tab, in the "Linking" section, locate the "Other Linker Flags" setting and add the "-ObjC" flag:
Future Enhancements(未来增强功能)
LRU memory cache cleanup instead of reset on memory warning
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。