Swift中如何为Lottie动画设置图片占位符并解决缓存问题?
解决Lottie动画加载时缓存导致占位符不生效的问题
问题根源
你当前代码中传递animationCache: nil时,Lottie会默认使用全局的LottieConfiguration.shared.animationCache,并非彻底禁用缓存;同时如果是远程动画URL,系统URLSession的默认缓存策略也会导致重复加载时直接读取本地缓存,跳过占位符逻辑。
修复方案
1. 彻底禁用Lottie动画缓存
使用EmptyAnimationCache()替代nil,明确告诉Lottie不使用任何缓存:
Animation.loadedFrom(url: url, closure: { [weak self] animation in guard let self = self else { return } if let animation = animation { self.animateView.imageProvider = DefaultImageProvider() // 重置默认图片提供者 self.animateView.animation = animation self.animateView.play() } else { self.animateView.imageProvider = Asset.placeholder.image as! AnimationImageProvider self.animateView.loopMode = .loop self.animateView.play() } }, animationCache: EmptyAnimationCache())
2. 强制忽略URL请求缓存(针对远程动画)
如果动画是远程URL,自定义URLRequest设置缓存策略,避免系统缓存影响:
// 构建忽略缓存的请求 let urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData) Animation.loadedFrom(request: urlRequest, closure: { [weak self] animation in guard let self = self else { return } if let animation = animation { self.animateView.imageProvider = DefaultImageProvider() self.animateView.animation = animation self.animateView.play() } else { self.animateView.imageProvider = Asset.placeholder.image as! AnimationImageProvider self.animateView.loopMode = .loop self.animateView.play() } }, animationCache: EmptyAnimationCache())
3. 优化占位符显示逻辑
提前在初始化阶段设置占位符,避免缓存动画直接覆盖占位符:
// 初始化时先显示占位符 override func viewDidLoad() { super.viewDidLoad() animateView.imageProvider = Asset.placeholder.image as! AnimationImageProvider animateView.loopMode = .loop animateView.play() // 之后再加载目标动画 let urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData) Animation.loadedFrom(request: urlRequest, closure: { [weak self] animation in guard let self = self else { return } if let animation = animation { self.animateView.imageProvider = DefaultImageProvider() self.animateView.animation = animation self.animateView.play() } // 加载失败则保持占位符,无需重复设置 }, animationCache: EmptyAnimationCache()) }
额外测试建议
- 测试前清空模拟器缓存:通过
模拟器菜单 > 设备 > 清除所有内容和设置,确保旧缓存被彻底清除。 - 若使用本地动画文件,可直接删除App后重新安装,避免本地文件缓存影响。
内容的提问来源于stack exchange,提问作者kkk
相关产品推荐
相关产品推荐

