swift中的SDWebimage - Kingfisher

在oc开发中,我们都会比较熟悉SDWebImage,而在swift中,Kingfisher充当了这个角色。

使用URL设置图像

let url = URL(string: "https://example.com/image.jpg")
imageView.kf.setImage(with: url)
思路:
  • 使用url.absoluteString作为key查询是否缓存了图片(先后查询内存和磁盘);
  • 如果找到,则显示缓存图片;
  • 若不存在,通过URL下载,并将下载的数据转换成image对象;
  • 缓存图片到内存,并保存在磁盘中;

背景图设置

let image = UIImage(named: "default_profile_icon")
imageView.kf.setImage(with: url, placeholder: image)

下载loading

imageView.kf.indicatorType = .activity
imageView.kf.setImage(with: url)

过渡动画

imageView.kf.setImage(with: url, options: [.transition(.fade(0.2))])

下载完成处理

imageView.kf.setImage(with: url) { result in
    // `result` is either a `.success(RetrieveImageResult)` or a `.failure(KingfisherError)`
    switch result {
    case .success(let value):
        // The image was set to image view:
        print(value.image)

        // From where the image was retrieved:
        // - .none - Just downloaded.
        // - .memory - Got from memory cache.
        // - .disk - Got from disk cache.
        print(value.cacheType)

        // The source object which contains information like `url`.
        print(value.source)

    case .failure(let error):
        print(error) // The error happens
    }
}

圆角图片

let processor = RoundCornerImageProcessor(cornerRadius: 20)
imageView.kf.setImage(with: url, options: [.processor(processor)])

缓存Cache

  • 默认情况下,使用图片url来作为key缓存,除非重新指定。
let resource = ImageResource(downloadURL: url, cacheKey: "cache_Key")
imageView.kf.setImage(with: resource)

查看缓存

let cache = ImageCache.default
let cached = cache.isCached(forKey: cacheKey)

// To know where the cached image is:
let cacheType = cache.imageCachedType(forKey: cacheKey)
// `.memory`, `.disk` or `.none`.

你可能感兴趣的:(swift中的SDWebimage - Kingfisher)