【iOS】SDWebImage

文章目录

前言

在写知乎日报项目时,遇到了图片加载和通过API异步加载图片的问题,在组内成员的引导下,去学习了SDWebImage开源库。

SDWebImage

SDWebImage 是一个用 Objective-C 编写的开源库,主要用于异步加载和缓存图片。

SDWebImage 提供了一个异步图片下载器,允许在后台线程下载图片,避免阻塞主线程。

SDWebImage 实现了异步的内存和磁盘缓存机制,具有自动缓存到期处理。

SDWebImage 支持包括 GIF 和 WebP 在内的多种图片格式,且能确保同一个 URL 的图片不会被重复下载,确保无效的 URL 不会被反复加载,支持后台图片解压缩处理,以减少主线程的负担。

SDWebImage 的主要组件包括:

UIImageView+WebCache:为 UIImageView 提供网络图片加载和缓存的扩展。

SDWebImageManager:作为下载器和缓存的桥梁,管理图片的下载和缓存。

SDWebImageDownloader:负责图片的下载操作。

SDImageCache:负责图片的缓存,包括内存缓存和磁盘缓存。

常用方法及简单用法示例

在使用SDWebImage库之前,首先要将其导入所需项目内。

然后在需要的文件里引用头文件:

objectivec 复制代码
#import "UIImageView+WebCache.h"

使用时,调用sd_setImageWithURL:方法缓存图片,这就是新版本的新方法,旧方法是setImageWithURL:。下面是常用的几个方法

  1. sd_setImageWithURL:
objectivec 复制代码
//图片缓存的基本代码
[self.image1 sd_setImageWithURL:imagePath1];
  1. sd_setImageWithURL: completed:
objectivec 复制代码
//用block 可以在图片加载完成之后做些事情
[self.image2 sd_setImageWithURL:imagePath2 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
      //在图片加载完成之后想触发的事情
      NSLog(@"加载完成");
}];
  1. sd_setImageWithURL: placeholderImage:
objectivec 复制代码
//给一张默认图片,先使用默认图片,当图片加载完成后再替换
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"]];
  1. sd_setImageWithURL: placeholderImage: completed:
objectivec 复制代码
//使用默认图片,而且用block 在完成后做一些事情
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {         
      NSLog(@"加载完成");        
}];
  1. sd_setImageWithURL: placeholderImage: options:
objectivec 复制代码
//options 选择方式
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"] options:SDWebImageRetryFailed];
//如果你只需要内存缓存,那么在options这里选择SDWebImageCacheMemoryOnly就可以了。

简单应用:

objectivec 复制代码
    NSURL *url = [NSURL URLWithString:@"https://news-at.zhihu.com/api/7/prefetch-launch-images/1080*1920"];
    self.imageView = [[UIImageView alloc] init];
    UIImage *placeholderImage = [UIImage imageNamed:@"placeholder"];
    [self.imageView sd_setImageWithURL:url placeholderImage:placeholderImage];
    
    [self.view addSubview:self.imageView];

总结

我在知乎日报编写中运用了这个库函数,但是我并未获取到图片(在模拟器上没加载出来),不清楚是API的问题还是代码哪里出了差错,还在研究,另外,我暂时只学习了SDWebImage的常用方法和基本用法,至于运用时可能碰见的其他问题,还有待发现和解决。

参考文章:iOS SDWebImage的使用

相关推荐
zstar-_2 小时前
FreeTex v0.2.0:功能升级/支持Mac
人工智能·python·macos·llm
安和昂2 小时前
【iOS】SDWebImage源码学习
学习·ios
ii_best2 小时前
按键精灵ios脚本新增元素功能助力辅助工具开发(三)
ios
ii_best6 小时前
按键精灵ios脚本新增元素功能助力辅助工具开发(二)
ios
ii_best6 小时前
按键精灵ios脚本新增元素功能助力辅助工具开发(一)
ios
struggle20257 小时前
continue通过我们的开源 IDE 扩展和模型、规则、提示、文档和其他构建块中心,创建、共享和使用自定义 AI 代码助手
javascript·ide·python·typescript·开源
仓颉编程语言9 小时前
仓颉Magic亮相GOSIM AI Paris 2025:掀起开源AI框架新热潮
人工智能·华为·开源·鸿蒙·仓颉编程语言
Swift社区12 小时前
Swift实战:如何优雅地从二叉搜索树中挑出最接近的K个值
开发语言·ios·swift
奋斗者1号12 小时前
开源 RPA 工具深度解析与官网指引
开源·rpa
GIS工具-gistools202112 小时前
Open Source Geospatial Content Management System -GeoNode
开源·gis·server