关于使用Kingfisher实现app图片缓存策略(Disk)

很多时候为了防止app显示图片重复下载,从而节约用户的流量,我们会考虑将下载好的一部分图片保存在本地,在OC中我们可以使用SDWebImage来实现自己的缓存机制,在SWIFT中我们也可以使用相应的第三方库Kingfisher来实现自己的缓存机制。

首先确定图片缓存到Disk的路劲,在Kingfisher中我们可以用

//缓存路径
        let imageCache = ImageCache(name: "myImageSpace")

自定义缓存路劲,一般来说,如果我们不对cache进行定义

let cache = KingfisherManager.sharedManager.cache

那么默认的可以储存的图片为无限 默认时间是一周,以上两项属性可以通过****cache.maxDiskCacheSize****和****maxCachePeriodInSecond****来进行设置
这里附带一个获取缓存大小的方法

// 获取硬盘缓存的大小cache.cache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in println("disk size in bytes: \(size)")}

这里主要涉及到的是缓存管理类ImageCache,demo

    public init(name: String, path: String? = nil) {
        
        if name.isEmpty {
            fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
        }
        
        let cacheName = "com.onevcat.Kingfisher.ImageCache.\(name)"
        memoryCache.name = cacheName
        
        let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
        diskCachePath = (dstPath as NSString).appendingPathComponent(cacheName)
        
        let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(name)"
        ioQueue = DispatchQueue(label: ioQueueName)
        
        let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue.\(name)"
        processQueue = DispatchQueue(label: processQueueName, attributes: .concurrent)
        
        ioQueue.sync { fileManager = FileManager() }
        
#if !os(macOS) && !os(watchOS)
        NotificationCenter.default.addObserver(
            self, selector: #selector(clearMemoryCache), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
        NotificationCenter.default.addObserver(
            self, selector: #selector(cleanExpiredDiskCache), name: .UIApplicationWillTerminate, object: nil)
        NotificationCenter.default.addObserver(
            self, selector: #selector(backgroundCleanExpiredDiskCache), name: .UIApplicationDidEnterBackground, object: nil)
#endif
    }

判断该路径下是否有相应的图片

    open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
        
        let options = options ?? KingfisherEmptyOptionsInfo
        let computedKey = key.computedKey(with: options.processor.identifier)
        
        return diskImage(forComputedKey: computedKey, serializer: options.cacheSerializer, options: options)
    }

如果不存在image,获取该image,并存入本地磁盘,返回所需数据

      KingfisherManager.shared.downloader.downloadImage(with: URL(string: urlString)!, options: nil, progressBlock: {(receivedSize, totalSize) in
                
                
            }, completionHandler: {(_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) in
                
                guard image != nil else {
                    print("获取图片失败")
                    return
                }
                //存入本地磁盘
                imageCache.store(image!, forKey: urlString)
                //返回数据
                image1 = image
            })

当然还有清楚缓存

        //清楚缓存
        //imageCache.clearDiskCache()

Kingfisher还提供了综合操作的相关方法,可以直接使用


        KingfisherManager.shared.retrieveImage(with: <#T##Resource#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> ()#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> ()#>)

当然最简单的直接用

imageVeiw.kf.setImage(with: ImageResource(downloadURL:URL(string: (model.image)!)!))

哈哈,这个最重要

你可能感兴趣的:(关于使用Kingfisher实现app图片缓存策略(Disk))