前言 Kingfisher
是一个 下载、缓存
网络图片的轻量级纯swift库,在swift中是一个SDWebImage的升级版
特征
异步下载和缓存图片
提供图片处理器和过滤器
内存和磁盘的多层缓存
扩展UIImageView/UIButton来设置图片,内置过渡动画
基本使用
直接设置一张url图片
1 2 3 if let url = URL(string: "http://mvimg2.meitudata.com/55fe3d94efbc12843.jpg") { imgView.kf.setImage(with: url) }
注:kingfisher
首先尝试从缓存中去取,如果没有,直接下载图片并且缓存下来备用;此外,kingfisher
默认使用 url
作为 cacheKey
以方便再次加载该图片时去缓存中根据 cacheKey
查找
指定给一个 cacheKey 缓存图片
1 2 let imageResource = ImageResource(downloadURL: url, cacheKey: "Custom_cache_key") imageView.kf.setImage(with: imageResource)
设置占位图片
1 2 3 if let url = URL(string: "http://mvimg2.meitudata.com/55fe3d94efbc12843.jpg") { imageView.kf.setImage(with: url, placeholder: placeholder_image, options: nil, progressBlock: nil, completionHandler: nil) }
下载完成回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 if let url = URL(string: "http://mvimg2.meitudata.com/55fe3d94efbc12843.jpg") { imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in image // 为 nil 时,表示下载失败 error // 为 nil 时,表示下载成功, 非 nil 时,就是下载失败的错误信息 cacheType // 缓存类型,是个枚举,分以下三种: // .none 图片还没缓存(也就是第一次加载图片的时候) // .memory 从内存中获取到的缓存图片(第二次及以上加载) // .disk 从磁盘中获取到的缓存图片(第二次及以上加载) imageUrl // 所要下载的图片的url }) }
加载菊花
1 2 3 4 5 6 7 8 9 10 public enum IndicatorType { // 默认没有菊花 case none // 使用系统菊花 case activity // 使用一张图片作为菊花,支持gif图 case image(imageData: Data) // 使用自定义菊花,要遵循Indicator协议 case custom(indicator: Indicator) }
1 2 imageView.kf.indicatorType = .activity imageView.kf.setImage(with: url)
1 2 3 4 let path = Bundle.main.path(forResource: "myImage", ofType: "gif")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) imageView.kf.indicatorType = .image(imageData: data) imageView.kf.setImage(with: url)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 let myIndicator = CustomIndicator() imageView.kf.indicatorType = .custom(indicator: myIndicator) imageView.kf.setImage(with: url) struct CustomIndicator: Indicator { var view: IndicatorView = UIView() func startAnimatingView() { view.isHidden = false } func stopAnimatingView() { view.isHidden = true } init() { view.backgroundColor = UIColor.magenta } }
根据实时下载图片的数据做进度条加载或者菊花加载(灵活,比例为:图片已下载数据 / 图片总数据)
1 2 3 4 5 6 7 8 9 imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: { (receivedData, totolData) in let percentage = (Float(receivedData) / Float(totolData)) * 100.0 print("downloading progress is: \(percentage)%") // 这里用进度条或者绘制view都可以,然后根据 percentage% 表示进度就行了 }, completionHandler: nil)
…