iOS 第三方框架-SDWebImage

时间:2023-03-09 05:52:29
iOS 第三方框架-SDWebImage
iOS中著名的牛逼的网络图片处理框架。包含的功能:图片下载、图片缓存、下载进度监听、gif处理等等。用法极其简单,功能十分强大,大大提高了网络图片的处理效率。国内超过90%的iOS项目都有它的影子。
项目地址
基本处理原理:
iOS 第三方框架-SDWebImage
1.面试题
1> 如何防止一个url对应的图片重复下载
* 查看“基本处理原理”上图

2> SDWebImage的默认缓存时长是多少?
* 1个星期

3> SDWebImage底层是怎么实现的?
* 查看“基本处理原理”上图

常用方法

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

SDWebImageOptions 参数说明

  1. SDWebImageRetryFailed : 下载失败后,会自动重新下载
  2. SDWebImageLowPriority : 当正在进行UI交互时,自动暂停内部的一些下载操作
  3. SDWebImageRetryFailed | SDWebImageLowPriority : 拥有上面2个功能

我们使用的时候,一般就是用第3点。实例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ID = @"app";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
} // 取出模型
HMApp *app = self.apps[indexPath.row]; // 设置基本信息
cell.textLabel.text = app.name;
cell.detailTextLabel.text = app.download; // 下载图片
NSURL *url = [NSURL URLWithString:app.icon];
UIImage *placeholder = [UIImage imageNamed:@"placeholder"]; SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority; [cell.imageView sd_setImageWithURL:url placeholderImage:placeholder options:options progress:^(NSInteger receivedSize, NSInteger expectedSize) { // 这个block可能会被调用多次
NSLog(@"下载进度:%f", (double)receivedSize / expectedSize);
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"----图片加载完毕---%@", image);
}];
return cell;
}

内存处理

由于图片是缓存在沙盒里,会有内存警告的时候。
/**
* 当app接收到内存警告
*/
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
SDWebImageManager *mgr = [SDWebImageManager sharedManager]; // 1.取消正在下载的操作
[mgr cancelAll]; // 2.清除内存缓存
[mgr.imageCache clearMemory];
}