代码改变世界

iOS 第三方框架-SDWebImage

  jiangys  阅读(1329)  评论(0编辑  收藏  举报
iOS中著名的牛逼的网络图片处理框架。包含的功能:图片下载、图片缓存、下载进度监听、gif处理等等。用法极其简单,功能十分强大,大大提高了网络图片的处理效率。国内超过90%的iOS项目都有它的影子。
项目地址
 
基本处理原理:
 
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];
}
复制代码

 

 
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示