Kingfisher-swift緩存圖片框架


Kingfisher是swift中加載網絡圖片的框架,類似於SDWebImage,加載緩存網絡圖片,兼容macOS, IOS

一、基本使用方法:

ima1.kf.setImage(with: url),它通過協議定義了kf,UIImageVIew實現了這個協議實際上就是本身

二、關於緩存圖片

基本策略:1內存中,2磁盤中,下載最新的緩存到內存和磁盤

存在磁盤中的是image轉成的data存儲

在內存中存的的是NSCache,使用它的原因:

1.NSCache類結合了各種自動刪除策略,以確保不會占用過多的系統內存

如果其它應用需要內存時,系統自動執行這些策略

當調用這些策略時,會從緩存中刪除一些對象,以最大限度減少內存的占用。

2.NSCache是線程安全的,我們可以在不同的線程中添加、刪除和查詢緩存中的對象,而不需要鎖定緩存區域。

不像NSMutableDictionary對象,一個緩存對象不會拷貝key對象。

 NSCache [key:value(StorageObject對象里邊有屬性key,屬性value)]

如何存在內存里的

通過一個單利對象存儲,單利中有屬性memoryStorage,里邊有個NSCache

KingfisherManager.shared

1.增加了一個清楚內存緩存的策略

通過一個定時器定期清除過期的緩存,默認為2分鍾(可以設定)清理一次

刪除緩存時間大於5分鍾(可以設定)的對象,保證了一個對象在內存中存在時間是5到7分鍾

2.默認的緩存對象最大個數是無限大

3.內存大小的celue

// Bitmap memory cost with bytes. 計算每個圖片的大小B

    var cost: Int {

        let pixel = Int(size.width * size.height * scale * scale)

        guard let cgImage = cgImage else {

            return pixel * 4

        }

        return pixel * cgImage.bitsPerPixel / 8

    }

最大占用內存數totalCostLimit 是 物理內存的1/4

let totalMemory = ProcessInfo.processInfo.physicalMemory

let costLimit = totalMemory / 4

三、 disk磁盤中緩存策略

每次進入后台時,和將要推出應用時  清理7天(可以設置)之前的緩存,如果緩存大於設定值的最大值則刪除最早緩存的data

磁盤中存取的是data

有關其中的緩存的key    是url  如果url中不包含具體圖片的名稱,但后台更改圖片但是url地址不變時不會加載中新圖片

 四、可配置的設置項

通過KingfisherOptionsInfo 可以配置一些設置

eg:只從內存中取,內存中沒有就直接下載,或者設置為直接下載最新的,設置請求類型等

所有內容如下:

/// Represents the available option items could be used in `KingfisherOptionsInfo`.
 public enum KingfisherOptionsInfoItems { /// Kingfisher will use the associated `ImageCache` object when handling related operations, /// including trying to retrieve the cached images and store the downloaded image to it.
 //目標圖片,修飾完處理器處理完之后的圖片最終圖片緩存,不指定會默認創建,可以設定最大緩存數等,過期時間默認為5分鍾也就是說取圖片時發現時5分鍾之前緩存的會重新下載圖片
 case targetCache(ImageCache) /// The `ImageCache` for storing and retrieving original images. If `originalCache` is /// contained in the options, it will be preferred for storing and retrieving original images. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. ///
 /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is /// applied in the option, the original image will be stored to this `originalCache`. At the /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, /// Kingfisher will try to search the original image to check whether it is already there. If found, /// it will be used and applied with the given processor. It is an optimization for not downloading /// the same image for multiple times.
 case originalCache(ImageCache) /// Kingfisher will use the associated `ImageDownloader` object to download the requested images.
 case downloader(ImageDownloader) /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `.forceRefresh` as well.
 case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used.
 case downloadPriority(Float) /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource.
 case forceRefresh /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory /// cache, then it will ignore the disk cache but download the image again from network. This is useful when /// you want to display a changeable image behind the same url at the same app session, while avoiding download /// it for multiple times.
 case fromMemoryCacheOrRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `.transition` option for more.
 case forceTransition /// If set, Kingfisher will only cache the value in memory but not in disk.
 case cacheMemoryOnly /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block.
 case waitForCache /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is /// not in cache, the image retrieving will fail with an error.
 case onlyFromCache /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen /// rendering to extract pixel information in background. This can speed up display, but will cost more time to /// prepare the image for using.
 case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks.
 @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") case callbackDispatchQueue(DispatchQueue?) /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. ///
 /// - Note: /// This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue.
 case callbackQueue(CallbackQueue) /// The associated value will be used as the scale factor when converting retrieved data to an image. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
 case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. ///
 /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, /// which uses more memory but only decode image frames once.
 case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the image download request. You can modify the request for some /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. /// The original request will be sent without any modification by default.
 case requestModifier(ImageDownloadRequestModifier) /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirect. You can modify the request for /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url /// mapping. /// The original redirection request will be sent without any modification by default.
 case redirectHandler(ImageDownloadRedirectHandler) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. /// If not set, the `DefaultImageProcessor.default` will be used.
 case processor(ImageProcessor) /// Supplies a `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// If not set, the `DefaultCacheSerializer.default` will be used.
 case cacheSerializer(CacheSerializer) /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being /// fetched from a cache, the modifier will run after the `CacheSerializer`. ///
 /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`.
 case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image.
 case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from an animated image file as a single image. /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. ///
 /// This option will be ignored if the target image is not animated image data.
 case onlyLoadFirstFrame /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original /// images if necessary. ///
 /// The original image will be only cached to disk storage.
 case cacheOriginalImage /// If set and a downloading error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed.
 case onFailureImage(Image?) /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage /// aggressively. By default this is not contained in the options, that means if the requested image is already /// in disk cache, Kingfisher will not try to load it to memory.
 case alsoPrefetchToMemory /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already /// has an image set. ///
 /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
 case loadDiskFileSynchronously /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item.
 case memoryCacheExpiration(StorageExpiration) /// The expiration extending setting for memory cache. The item expiration time will be incremented by this value after access. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options.
 case memoryCacheAccessExtendingExpiration(ExpirationExtending) /// The expiration setting for memory cache. By default, the underlying `DiskStorage.Backend` uses the /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item.
 case diskCacheExpiration(StorageExpiration) /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of /// blocking the UI, especially if the processor needs a lot of time to run).
 case processingQueue(CallbackQueue) /// Enable progressive image loading, Kingfisher will use the `ImageProgressive` of
 case progressiveJPEG(ImageProgressive) }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM