Kingfisher学习笔记
Kingfisher是一个使用Swift编写的用于下载和缓存图片的iOS库,作者王巍受SDWebImage的启发开发了这个纯Swift的库。Kingfisher的完整特性可以从下面的链接中获取,本文主要是学习项目源码的一些心得。
https://github.com/onevcat/Kingfisher
kf_xxx >> kf.xxx
参考[RxCocoa] Move from rx_
prefix to a rx.
proxy (for Swift 3 update ?
传统的Objective-C语法对于扩展的method,推荐使用kf_xxx方式命名,但是这种命名不太符合Swift的风格,且看起来很丑。因此越来越多的Swift项目开始参考LazySequence
模式,使用类似下面的风格:
myArray.map { ... }
myArray.lazy.map { ... }
Kingfisher也由kf_xxx转向了kf.xxx风格,如imageView?.kf.indicatorType = .activity
。要实现这个机制,需要以下几步:
-
实现一个作为Proxy的class/struct
这个Proxy仅将真实的对象包裹起来,不做任何实际的操作。Kingfisher使用的
Kingfisher
这个class
,定义如下:public final class Kingfisher<Base> { public let base: Base public init(_ base: Base) { self.base = base } }
-
定义一个Protocol用于提供
.kf
的方法Kingfisher是使用了
KingfisherCompatible
,它有两个关键点:- 定义一个名为
kf
的property。这不是必须的,实际上KingfisherCompatible
可以为一个空protocol,只要我们实现了下一步即可。 - 提供一个
kf
的默认实现,返回一个新建的Proxy对象,即Kingfisher
对象
定义如下:
/** A type that has Kingfisher extensions. */ public protocol KingfisherCompatible { associatedtype CompatibleType var kf: CompatibleType { get } } public extension KingfisherCompatible { public var kf: Kingfisher<Self> { get { return Kingfisher(self) } } }
- 定义一个名为
-
将Protocol加载到所需的Base类上
定义一个Base类的extension即可。比如使用下面的代码后,我们就可以通过使用诸如imageView.kf
的代码了。extension Image: KingfisherCompatible { } extension ImageView: KingfisherCompatible { } extension Button: KingfisherCompatible { }
-
通过Extension + where Base实现Base类的特定代码
比如实现下面的代码后,我们就可以通过调用
imageView.kf.webURL
获取imageView的webURL了。
需要注意的是,使用objc_getAssociatedObject
或objc_setAssociatedObject
时,一定与base
关联,而不是self
!因为从.kf
的实现中也可以知道,每次调用imageView.kf
时,实际上返回的都是一个全新的Kingfisher
。extension Kingfisher where Base: ImageView { public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } }
ImageDownloader
ImageDownloader是这个库的两大核心之一,另一个是ImageCache。
ImageDownloader represents a downloading manager for requesting the image with a URL from server.
ImageFetchLoad
它是ImageDownloader的一个内部class,主要用于避免一个URL的资源被同时下载多次。定义如下:
class ImageFetchLoad {
var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]()
var responseData = NSMutableData()
var downloadTaskCount = 0
var downloadTask: RetrieveImageDownloadTask?
var cancelSemaphore: DispatchSemaphore?
}
这个类通过ImageDownloader.fetchLoads与某个URL挂钩。对于一个URL,如果用户反复下载,
-
若正在下载这个URL的资源,则用户试图再次下载时,ImageDownloader不会真的下载,而是令ImageFetchLoad .downloadTaskCount++。
-
若上一次的下载已经结束,这个URL会被再次下载。因为一次下载结束时会通过processImage >> cleanFetchLoad将这个URL对应的ImageFetchLoad清除。
Properties
fetchLoads
是一个[URL: ImageFetchLoad],如上所说,用于记录URL和ImageFetchLoad的关系。
存在3个不同的DispatchQueue
- barrierQueue
concurrent
用于thread safe地操作fetchLoads
- processQueue:
concurrent
数据下载完成后,用于在后台处理数据,避免阻塞mian thread - cancelQueue
serial
跟ImageFetchLoad.cancelSemaphore有关。从目前来看,仅当一个URL的fetchLoad被创建 && 还没来得及开始下载(downloadTaskCount == 0)时,若该URL又有一个下载请求过来了,我们会在cancelQueue中让其等待起来。若之前的那个下载请求失败了,才会启动本次的下载。
if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 {
if fetchLoad.cancelSemaphore == nil {
fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0)
}
cancelQueue.async {
_ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture)
fetchLoad.cancelSemaphore = nil
prepareFetchLoad()
}
} else {
prepareFetchLoad()
}
private func callCompletionHandlerFailure(error: Error, url: URL) {
guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else {
return
}
// We need to clean the fetch load first, before actually calling completion handler.
cleanFetchLoad(for: url)
var leftSignal: Int
repeat {
leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0
} while leftSignal != 0
for content in fetchLoad.contents {
content.options.callbackDispatchQueue.safeAsync {
content.callback.completionHandler?(nil, error as NSError, url, nil)
}
}
}
sessionHandler
用于实现URLSessionDataDelegate,并避免由于session导致的retain cycle。https://github.com/onevcat/Kingfisher/issues/235
APIs
downloadImage()
对外的API主要是这个方法,定义如下:
/**
Download an image with a URL and option.
- parameter url: Target URL.
- parameter retrieveImageTask: The task to cooporate with cache. Pass `nil` if you are not trying to use downloader and cache.
- parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
- parameter progressBlock: Called when the download progress updated.
- parameter completionHandler: Called when the download progress finishes.
- returns: A downloading task. You could call `cancel` on it to stop the downloading process.
*/
@discardableResult
open func downloadImage(with url: URL,
retrieveImageTask: RetrieveImageTask? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: ImageDownloaderProgressBlock? = nil,
completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask?
ImageCache
ImageCache是这个库的两大核心之一,另一个是ImageDownloader。
ImageCache represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You could use an ImageCache object to manipulate memory and disk cache for Kingfisher.
ImageCache的原理比较简单。比较值得学习的是它里面用到了2个单独的DispatchQueue,以免堵塞主线程。
- ioQueue
serial
用于处理disk读写相关的操作。 - processQueue
concurrent
用于对下载的数据做decode。
ImageProcessor
An ImageProcessor would be used to convert some downloaded data to an image.
它是一个Protocol,用于将下载的数据转换为image,定义如下:
public protocol ImageProcessor {
/// Identifier of the processor.
var identifier: String { get }
/// Process an input `ImageProcessItem` item to an image for this processor.
///
/// - parameter item: Input item which will be processed by `self`
/// - parameter options: Options when processing the item.
///
/// - returns: The processed image.
///
/// - Note: The return value will be `nil` if processing failed while converting data to image.
/// If input item is already an image and there is any errors in processing, the input
/// image itself will be returned.
/// - Note: Most processor only supports CG-based images.
/// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS.
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
}
Kingfisher提供了以下默认的实现。
DefaultImageProcessor
The default processor. It convert the input data to a valid image. Images of .PNG, .JPEG and .GIF format are supported. If an image is given, DefaultImageProcessor will do nothing on it and just return that image.
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image
case .data(let data):
return Kingfisher<Image>.image(
data: data,
scale: options.scaleFactor,
preloadAllAnimationData: options.preloadAllAnimationData,
onlyFirstFrame: options.onlyLoadFirstFrame)
}
}
GeneralProcessor
private class。主要用于将两个ImageProcessor合并起来。这个合并很精巧,它定义了一个内部block p,初始化时p会hold住两个旧的ImageProcessor,process时会逐一使用它们。
public extension ImageProcessor {
/// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
/// will be "\(self.identifier)|>\(another.identifier)".
///
/// - parameter another: An `ImageProcessor` you want to append to `self`.
///
/// - returns: The new `ImageProcessor` will process the image in the order
/// of the two processors concatenated.
public func append(another: ImageProcessor) -> ImageProcessor {
let newIdentifier = identifier.appending("|>\(another.identifier)")
return GeneralProcessor(identifier: newIdentifier) {
item, options in
if let image = self.process(item: item, options: options) {
return another.process(item: .image(image), options: options)
} else {
return nil
}
}
}
}
typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
fileprivate struct GeneralProcessor: ImageProcessor {
let identifier: String
let p: ProcessorImp
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return p(item, options)
}
}
其他ImageProcessor
其他的ImageProcessor包括:
- RoundCornerImageProcessor
- ResizingImageProcessor
- BlurImageProcessor
- OverlayImageProcessor
- TintImageProcessor
- ColorControlsProcessor
- BlackWhiteProcessor
- CroppingImageProcessor
以上这些Processor,对于输入的ImageProcessItem,如果item
- 类型为image,则直接调用Image.kf的相关代码
- 类型为data,则先使用DefaultImageProcessor将其转换为image,再调用Image.kf的相关代码
Tips
Collection
- Collection可以相加。
如[1, 2, 3] + [4, 5] >> [1, 2, 3, 4, 5] - 通过在Extension中设定Collection的Iterator.Element,可以实现很多便利的方法。
比如实现下面的extension后,我们就可以直接使用options.targetCache.
public extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
/// The target `ImageCache` which is used.
public var targetCache: ImageCache {
if let item = lastMatchIgnoringAssociatedValue(.targetCache(.default)),
case .targetCache(let cache) = item
{
return cache
}
return ImageCache.default
}
}
- 巧用ArraySlice取代Array
例如,ImagePrefetcher的pendingResources用于记录prefetchResources中还有多少没有fetch,因此我们可以将它定义为ArraySlice,而非Array。这么做的好处在与可以避免没必要的复制。
public init(resources: [Resource],
options: KingfisherOptionsInfo? = nil,
progressBlock: PrefetcherProgressBlock? = nil,
completionHandler: PrefetcherCompletionHandler? = nil)
{
prefetchResources = resources
pendingResources = ArraySlice(resources)
。。。。
}
public func start()
{
。。。
let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
for _ in 0 ..< initialConcurentDownloads {
if let resource = self.pendingResources.popFirst() {
self.startPrefetching(resource)
}
}
}
DispatchQueue
- safyAsync
直接调用DispatchQueue.async(block)时,并不能保证block被执行的时间,我们在主线程上调用async通常是为了更新UI,直接调用block会更及时。
extension DispatchQueue {
// This method will dispatch the `block` to self.
// If `self` is the main queue, and current thread is main thread, the block
// will be invoked immediately instead of being dispatched.
func safeAsync(_ block: @escaping ()->()) {
if self === DispatchQueue.main && Thread.isMainThread {
block()
} else {
async { block() }
}
}
}
- ioQueue && processQueue
对于会消耗比较多时间的操作,比如文件的io和图片的process,我们可以使用单独的Queue来进行操作,这样可以避免阻塞主线程。
在使用这种线程时,可以搭配.barrier来解决Reader-Writer问题。