• 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)
     }
  • 相关阅读:
    【bzoj2653】【middle】【主席树+二分答案】
    Codeforces 464E. The Classic Problem
    关于主席树的入门,讲解和题单
    BZOJ3531-[Sdoi2014]旅行(树剖+线段树动态开点)
    [bzoj3123][洛谷P3302] [SDOI2013]森林(树上主席树+启发式合并)
    1018_两个圆相交的面积
    String对象中常用的方法
    张爱玲写的信
    React Native拆包及热更新方案 · Solartisan
    vue项目实战
  • 原文地址:https://www.cnblogs.com/duzhaoquan/p/11556755.html
Copyright © 2020-2023  润新知