iOS 轻量化动态图像下载缓存框架实现

简介: 日常开发过程中,图片的下载会占用大量的带宽,图片的加载会消耗大量的性能和内存,正确的使用图片显得尤为重要。 同样也经常需要在各类型控件上读取网络图片和处理本地图片,例如:UIImageView、UIBtton、NSImageView、NSButton等等。

一、背景

日常开发过程中,图片的下载会占用大量的带宽,图片的加载会消耗大量的性能和内存,正确的使用图片显得尤为重要。
同样也经常需要在各类型控件上读取网络图片和处理本地图片,例如:UIImageView、UIBtton、NSImageView、NSButton等等。
这时候有个从网络下载和缓存图像库就会便利太多太多,很多人这时候会说,对于这块也有很多比较优秀的开源库,比如 KingfisherYYWebImageSDWebImage等等。

0 0. 框架由来,

  • 本来之前呢只是想实现一个如何播放GIF,于是乎就出现第一版对任意控件实现播放GIF功能,这边只需要支持 AsAnimatable 即可快速达到支持播放GIF功能;
  • 后面Boss居然又说需要对GIF图支持注入滤镜功能,于是乎又修改底层,对播放的GIF图实现滤镜功能,于是之前写的滤镜库 Harbeth 即将闪亮登场;
  • 然后Boss又说,首页banner需要图像和GIF混合显示,索性就又来简单封装显示网络图像,然后根据 AssetType 来区分是属于网图还是GIF图,以达到混合显示网络图像和网络GIF以及本地图像和本地GIF混合播放功能;
  • 起初也只是简单的去下载资源Data用于显示图像,这时候boss又要搞事情了,图像显示有点慢,于是乎又开始写网络下载模块 DataDownloader 和磁盘缓存模块 Cached ,对于已下载的图像存储于磁盘缓存方便后续再次显示,同样的网络链接地址同时下载时不会重复下载,下载完成后统一分发响应,对于下载部分资源进行断点续载功能;
  • 慢慢越写越发现这玩意不就是一个图像库嘛,so 它就这么的孕育而生了!!!

备注:作为参考对象,当然这里面会有一些 Kingfisher 的影子,so 再次感谢猫神!!也学到不少新东西,Thanks!

先贴地址:https://github.com/yangKJ/ImageX

tutieshi_640x1137_3s.gif

待完成功能:

  • 网络资源分片下载
  • 控制下载最大并发量
  • 低数据模式
  • 图像解码优化
  • 位图展示动画效果

实现方案

这边主要就是分为以下几大模块,网络下载模块资源缓存模块动态图播放模块控件展示模块解码器模块 以及 配置模块等;

这边对于资源缓存模块,已独立封装成库 Lemons 来使用,支持磁盘和内存缓存,同时也支持对待存储数据进行压缩处理从而占用更小存储空间,同时也会对磁盘数据进行时间过期和达到最大缓存空间的自动清理。

如何播放动态图像

对于这块,核心其实就是使用 CADisplayLink 不断刷新和更新动画帧图,然后对不同的控件去设置显示图像资源;

主要就是针对不同对象设置显示内容:

  • UIImageView:imagehighlightedImage
  • NSImageVIew:image
  • UIButton:imagebackgroundImage
  • NSButton:imagealternateImage
  • WKInterfaceImage:image

对于UIView没有上述属性显示,so 这边对layer.contents设置也是同样能达到该效果。

如何下载网络资源

对于网络图像显示,不可获取的就是对于资源的下载。

最开始的简单版,

let task = URLSession.shared.dataTask(with: url) {
   
    (data, _, error) in
    switch (data, error) {
   
   
    case (.none, let error):
        failed?(error)
    case (let data?, _):
        DispatchQueue.main.async {
   
   
            self.displayImage(data: data, filters: filters, options: options)
        }
        let zipData = options.cacheDataZip.compressed(data: data)
        let model = CacheModel(data: zipData)
        storager.storeCached(model, forKey: key, options: options.cacheOption)
    }
}
task.resume()

鉴于boss说的显示有点慢,能优化不。于是开始就对网络下载模块开始优化,网络数据共享和断点续下功能就孕育而生,后续再来补充分片下载功能,进一步提升网络下载速率。

网络共享

  • 对于网络共享,这边其实就是采用一个单例 Networking 来设计,然后对需要下载的资源和回调响应进行存储,以链接地址md5作为key来管理查找,当数据下载回来之后,分别分发给回调响应即可,同时删除缓存的下载器和回调响应对象;

核心代码,下载过来的数据分发处理。

let downloader = DataDownloader(request: request, named: key, retry: retry, interval: interval) {
   
   
    for call in cacheCallBlocks where key == call.key {
   
   
        switch $0 {
   
   
        case .downloading(let currentProgress):
            let rest = DataResult(key: key, url: url, data: {
   
   mathJaxContainer[0]}2, downloadStatus: .downloading)
            call.block.progress?(currentProgress)
            call.block.download(.success(rest))
        case .complete:
            let rest = DataResult(key: key, url: url, data: {
   
   mathJaxContainer[1]}2, downloadStatus: .complete)
            call.block.progress?(1.0)
            call.block.download(.success(rest))
        case .failed(let error):
            call.block.download(.failure(error))
        case .finished(let error):
            call.block.download(.failure(error))
        }
    }
    switch $0 {
   
   
    case .complete, .finished:
        self.removeDownloadURL(with: key)
    case .failed, .downloading:
        break
    }
}

断点续下

  • 对于断点续下功能,这边是采用文件 Files 来实时写入存储已下载的资源,下载再下载到同样数据时刻,即先取出上次已经下载数据,然后从该位置再次下载未下载完整的数据资源即可。

核心代码,读取上次下载数据然后设置本次下载偏移量。

private func reset() {
   
   
    self.mutableData = Data()
    self.lastDate = Date()
    self.offset = self.files.fileCurrentBytes()
    if self.offset > 0 {
   
   
        if let data = self.files.readData() {
   
   
            self.mutableData.append(data)
            let requestRange = String(format: "bytes=%llu-", self.offset)
            self.request.addValue(requestRange, forHTTPHeaderField: "Range")
        } else {
   
   
            self.offset = 0
            try? self.files.removeFileItem()
        }
    }
}
  • 当然这边也对于网络下载失败,做了下载重试 DelayRetry 操作;

如何使用

  • 使用流程基本可以参考猫神所著Kingfisher,同样该库也采用这种模式,这样也方便大家使用习惯;

基本使用

let url = URL(string: "https://example.com/image.png")!
imageView.mt.setImage(with: url)

设置不同参数使用

var options = ImageXOptions(moduleName: "Component Name") // 组件化需模块名
options.placeholder = .image(R.image("IMG_0020")!) // 占位图
options.contentMode = .scaleAspectBottomRight // 填充模式
options.Animated.loop = .count(3) // 循环播放3次
options.Animated.bufferCount = 20 // 缓存20帧
options.Animated.frameType = .animated //  
options.Cache.cacheOption = .disk // 采用磁盘缓存
options.Cache.cacheCrypto = .sha1 // 加密
options.Cache.cacheDataZip = .gzip // 压缩数据
options.Network.retry = .max3s // 网络失败重试
options.Network.timeoutInterval = 30 // 网络超时时间
options.Animated.setPreparationBlock(block: {
   
    [weak self] _ in
    // do something..
})
options.Animated.setAnimatedBlock(block: {
   
    _ in
    // play is complete and then do something..
})
options.Network.setNetworkProgress(block: {
   
    _ in
    // download progress..
})
options.Network.setNetworkFailed(block: {
   
    _ in
    // download failed.
})

let links = [``GIF URL``, ``Image URL``, ``GIF Named``, ``Image Named``]
let named = links.randomElement() ?? ""
// Setup filters.
let filters: [C7FilterProtocol] = [
    C7SoulOut(soul: 0.75),
    C7Storyboard(ranks: 2),
]
imageView.mt.setImage(with: named, filters: filters, options: options)

快速让控件播放动图和添加滤镜

  • 只需要支持 AsAnimatable 协议,即可快速达到支持播放动态图像功能;
class AnimatedView: UIView, AsAnimatable {
   
   
    ...
}
let filters: [C7FilterProtocol] = [
    C7WhiteBalance(temperature: 5555),
    C7Storyboard(ranks: 3)
]
let data = R.gifData("pikachu")
var options = ImageXOptions()
options.Animated.loop = .forever
options.placeholder = .view(placeholder)
animatedView.play(data: data, filters: filters, options: options)

配置额外参数

  • 鉴于后续参数的增加,因此采用 ImageXOptions 来传递其余参数,方便扩展和操作;

基本公共参数

public struct ImageXOptions {
   
   

    public static var `default` = ImageXOptions()

    /// Additional parameters that need to be set to play animated images.
    public var Animated: ImageXOptions.Animated = ImageXOptions.Animated.init()

    /// Download additional parameters that need to be configured to download network resources.
    public var Network: ImageXOptions.Network = ImageXOptions.Network.init()

    /// Caching data from the web need to be configured parameters.
    public var Cache: ImageXOptions.Cache = ImageXOptions.Cache.init()

    /// Appoint the decode or encode coder.
    public var appointCoder: ImageCoder?

    /// Placeholder image. default gray picture.
    public var placeholder: ImageX.Placeholder = .none

    /// Content mode used for resizing the frame image.
    /// When this property is `original`, modifying the thumbnail pixel size will not work.
    public var contentMode: ImageX.ContentMode = .original

    /// Whether or not to generate the thumbnail images.
    /// Defaults to CGSizeZero, Then take the size of the displayed control size as the thumbnail pixel size.
    public var thumbnailPixelSize: CGSize = .zero

    /// 做组件化操作时刻,解决本地GIF或本地图片所处于另外模块从而读不出数据问题。😤
    /// Do the component operation to solve the problem that the local GIF or Image cannot read the data in another module.
    public let moduleName: String

    /// Instantiation of GIF configuration parameters.
    /// - Parameters:
    ///   - moduleName: Do the component operation to solve the problem that the local GIF cannot read the data in another module.
    public init(moduleName: String = "ImageX") {
   
   
        self.moduleName = moduleName
    }
}

播放动态图像配置参数

extension ImageXOptions {
   
   

    public struct Animated {
   
   

        /// Desired number of loops. Default is ``forever``.
        public var loop: ImageX.Loop = .forever

        /// Animated image sources become still image display of appoint frames.
        /// After this property is not ``.animated``, it will become a still image.
        public var frameType: ImageX.FrameType = .animated

        /// The number of frames to buffer. Default is 50.
        /// A high number will result in more memory usage and less CPU load, and vice versa.
        public var bufferCount: Int = 50

        /// Maximum duration to increment the frame timer with.
        public var maxTimeStep = 1.0

        public init() {
   
    }

        internal var preparation: ((_ res: ImageX.GIFResponse) -> Void)?
        /// Ready to play time callback.
        /// - Parameter block: Prepare to play the callback.
        public mutating func setPreparationBlock(block: @escaping ((_ res: ImageX.GIFResponse) -> Void)) {
   
   
            self.preparation = block
        }

        internal var animated: ((_ loopDuration: TimeInterval) -> Void)?
        /// GIF animation playback completed.
        /// - Parameter block: Complete the callback.
        public mutating func setAnimatedBlock(block: @escaping ((_ loopDuration: TimeInterval) -> Void)) {
   
   
            self.animated = block
        }
    }
}

网络数据下载配置参数

extension ImageXOptions {
   
   

    public struct Network {
   
   

        /// Network max retry count and retry interval, default max retry count is ``3`` and retry ``3s`` interval mechanism.
        public var retry: ImageX.DelayRetry = .max3s

        /// Web images or GIFs link download priority.
        public var downloadPriority: Float = URLSessionTask.defaultPriority

        /// The timeout interval for the request. Defaults to 20.0
        public var timeoutInterval: TimeInterval = 20

        /// Network resource data download progress response interval.
        public var downloadInterval: TimeInterval = 0.02

        public init() {
   
    }

        internal var failed: ((_ error: Error) -> Void)?
        /// Network download task failure information.
        /// - Parameter block: Failed the callback.
        public mutating func setNetworkFailed(block: @escaping ((_ error: Error) -> Void)) {
   
   
            self.failed = block
        }

        internal var progressBlock: ((_ currentProgress: CGFloat) -> Void)?
        /// Network data task download progress.
        /// - Parameter block: Download the callback.
        public mutating func setNetworkProgress(block: @escaping ((_ currentProgress: CGFloat) -> Void)) {
   
   
            self.progressBlock = block
        }
    }
}

缓存资源配置参数

extension ImageXOptions {
   
   

    public struct Cache {
   
   

        /// Weather or not we should cache the URL response. Default is ``diskAndMemory``.
        public var cacheOption: Lemons.CachedOptions = .diskAndMemory

        /// Network data cache naming encryption method, Default is ``md5``.
        public var cacheCrypto: Lemons.CryptoType = .md5

        /// Network data compression or decompression method, default ``gzip``.
        /// This operation is done in the subthread.
        public var cacheDataZip: ImageX.ZipType = .gzip

        public init() {
   
    }
    }
}

总结

本文只是对网络图像和GIF显示的轻量化解决方案,让网图显示更加便捷,方便开发和后续迭代修改。实现方案还有许多可以改进的地方;
欢迎大家来使用该框架,然后指正修改亦或者大家有什么需求也可提出来,后续慢慢补充完善;
也欢迎大神来帮忙使用优化此库,再次感谢!!!

本库使用的滤镜库 Harbeth 和磁盘缓存库 Lemons 也欢迎大家使用;


对于如何使用和设计原理先简单介绍出来,关于后续功能和优化再慢慢介绍!

觉得有帮助的铁子,就给我点个星🌟支持一哈,谢谢铁子们~
本文图像滤镜框架传送门 ImageX 地址。
有什么问题也可以直接联系我,邮箱 yangkj310@gmail.com

相关文章
|
19天前
|
安全 数据安全/隐私保护 iOS开发
基于iOS的动态权限管理实现
【4月更文挑战第9天】 随着移动互联网的快速发展,用户对应用程序的隐私安全要求越来越高。在iOS平台中,如何实现动态权限管理成为了开发者关注的焦点。本文将详细介绍一种基于iOS的动态权限管理实现方法,通过使用Core Motion框架和Notification Center,实现对用户位置信息的实时监控和动态权限申请。
|
6天前
|
存储 缓存 安全
基于iOS平台的高效图片缓存策略实现
【4月更文挑战第22天】 在移动应用开发中,图片资源的加载与缓存是影响用户体验的重要因素之一。尤其对于iOS平台,由于设备存储空间的限制以及用户对流畅性的高要求,设计一种合理的图片缓存策略显得尤为关键。本文将探讨在iOS环境下,如何通过使用先进的图片缓存技术,包括内存缓存、磁盘缓存以及网络请求的优化,来提高应用的性能和响应速度。我们将重点分析多级缓存机制的设计与实现,并对可能出现的问题及其解决方案进行讨论。
|
6天前
|
存储 缓存 算法
实现iOS平台的高效图片缓存策略
【4月更文挑战第22天】在移动应用开发中,图片资源的处理是影响用户体验的重要因素之一。特别是对于图像资源密集型的iOS应用,如何有效地缓存图片以减少内存占用和提升加载速度,是开发者们面临的关键挑战。本文将探讨一种针对iOS平台的图片缓存策略,该策略通过结合内存缓存与磁盘缓存的机制,并采用先进的图片解码和异步加载技术,旨在实现快速加载的同时,保持应用的内存效率。
|
19天前
|
存储 缓存 iOS开发
基于iOS的高效图片缓存策略实现
【4月更文挑战第9天】在移动应用开发中,图片资源的加载与缓存是影响用户体验的重要因素之一。特别是对于iOS平台,合理设计图片缓存策略不仅能够提升用户浏览图片时的流畅度,还能有效降低应用程序的内存压力。本文将介绍一种针对iOS环境优化的图片缓存技术,该技术通过多级缓存机制和内存管理策略,实现了图片快速加载与低内存消耗的目标。我们将从系统架构、关键技术细节以及性能评估等方面展开讨论,为开发者提供一套实用的图片缓存解决方案。
18 0
|
24天前
|
存储 缓存 iOS开发
实现iOS平台的高效图片缓存策略
【4月更文挑战第4天】在移动应用开发中,图片资源的加载与缓存是影响用户体验的关键因素之一。尤其对于iOS平台,由于设备存储和内存资源的限制,设计一个高效的图片缓存机制尤为重要。本文将深入探讨在iOS环境下,如何通过技术手段实现图片的高效加载与缓存,包括内存缓存、磁盘缓存以及网络层面的优化,旨在为用户提供流畅且稳定的图片浏览体验。
|
25天前
|
开发工具 Swift iOS开发
利用SwiftUI构建动态用户界面:iOS开发新范式
【4月更文挑战第3天】 随着苹果不断推进其软件开发工具的边界,SwiftUI作为一种新兴的编程框架,已经逐渐成为iOS开发者的新宠。不同于传统的UIKit,SwiftUI通过声明式语法和强大的功能组合,为创建动态且响应式的用户界面提供了一种更加简洁高效的方式。本文将深入探讨如何利用SwiftUI技术构建具有高度自定义能力和响应性的用户界面,并展示其在现代iOS应用开发中的优势和潜力。
|
人工智能 文字识别 API
iOS MachineLearning 系列(4)—— 静态图像分析之物体识别与分类
本系列的前几篇文件,详细了介绍了Vision框架中关于静态图片区域识别的内容。本篇文章,我们将着重介绍静态图片中物体的识别与分类。物体识别和分类也是Machine Learning领域重要的应用。通过大量的图片数据进行训练后,模型可以轻易的分析出图片的属性以及图片中物体的属性。
236 0
|
算法 API iOS开发
iOS MachineLearning 系列(3)—— 静态图像分析之区域识别
本系列的前一篇文章介绍了如何使用iOS中自带的API对图片中的矩形区域进行分析。在图像静态分析方面,矩形区域分析是非常基础的部分。API还提供了更多面向应用的分析能力,如文本区域分析,条形码二维码的分析,人脸区域分析,人体分析等。本篇文章主要介绍这些分析API的应用。
218 0
|
9月前
|
Android开发 iOS开发 Windows
无影产品动态|iOS & Android客户端6.0.0版本发布,提升触控灵敏度,操作体验更丝滑
无影ios & Android客户端6.0.0版本发布!移动端触控体验更舒适,用户操作更便捷,一起来看看!
678 0
无影产品动态|iOS & Android客户端6.0.0版本发布,提升触控灵敏度,操作体验更丝滑
|
9月前
|
C语言 C++ iOS开发
iOS中C++静态全局变量的动态初始化时序
一个由于C++初始化失败导致Realm初始化失败的Crash
136 1

热门文章

最新文章