This commit is contained in:
DDIsFriend
2023-08-24 16:46:39 +08:00
parent 887a468768
commit 1a0943017a
139 changed files with 24162 additions and 13640 deletions

View File

@@ -0,0 +1,132 @@
//
// CacheSerializer.swift
// Kingfisher
//
// Created by Wei Wang on 2016/09/02.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
/// An `CacheSerializer` is used to convert some data to an image object after
/// retrieving it from disk storage, and vice versa, to convert an image to data object
/// for storing to the disk storage.
public protocol CacheSerializer {
/// Gets the serialized data from a provided image
/// and optional original data for caching to disk.
///
/// - Parameters:
/// - image: The image needed to be serialized.
/// - original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
/// - Returns: The data object for storing to disk, or `nil` when no valid
/// data could be serialized.
func data(with image: KFCrossPlatformImage, original: Data?) -> Data?
/// Gets an image from provided serialized data.
///
/// - Parameters:
/// - data: The data from which an image should be deserialized.
/// - options: The parsed options for deserialization.
/// - Returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
/// Whether this serializer prefers to cache the original data in its implementation.
/// If `true`, after creating the image from the disk data, Kingfisher will continue to apply the processor to get
/// the final image.
///
/// By default, it is `false` and the actual processed image is assumed to be serialized to the disk.
var originalDataUsed: Bool { get }
}
public extension CacheSerializer {
var originalDataUsed: Bool { false }
}
/// Represents a basic and default `CacheSerializer` used in Kingfisher disk cache system.
/// It could serialize and deserialize images in PNG, JPEG and GIF format. For
/// image other than these formats, a normalized `pngRepresentation` will be used.
public struct DefaultCacheSerializer: CacheSerializer {
/// The default general cache serializer used across Kingfisher's cache.
public static let `default` = DefaultCacheSerializer()
/// The compression quality when converting image to a lossy format data. Default is 1.0.
public var compressionQuality: CGFloat = 1.0
/// Whether the original data should be preferred when serializing the image.
/// If `true`, the input original data will be checked first and used unless the data is `nil`.
/// In that case, the serialization will fall back to creating data from image.
public var preferCacheOriginalData: Bool = false
/// Returnes the `preferCacheOriginalData` value. When the original data is used, Kingfisher needs to re-apply the
/// processors to get the desired final image.
public var originalDataUsed: Bool { preferCacheOriginalData }
/// Creates a cache serializer that serialize and deserialize images in PNG, JPEG and GIF format.
///
/// - Note:
/// Use `DefaultCacheSerializer.default` unless you need to specify your own properties.
///
public init() { }
/// - Parameters:
/// - image: The image needed to be serialized.
/// - original: The original data which is just downloaded.
/// If the image is retrieved from cache instead of
/// downloaded, it will be `nil`.
/// - Returns: The data object for storing to disk, or `nil` when no valid
/// data could be serialized.
///
/// - Note:
/// Only when `original` contains valid PNG, JPEG and GIF format data, the `image` will be
/// converted to the corresponding data type. Otherwise, if the `original` is provided but it is not
/// If `original` is `nil`, the input `image` will be encoded as PNG data.
public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
if preferCacheOriginalData {
return original ??
image.kf.data(
format: original?.kf.imageFormat ?? .unknown,
compressionQuality: compressionQuality
)
} else {
return image.kf.data(
format: original?.kf.imageFormat ?? .unknown,
compressionQuality: compressionQuality
)
}
}
/// Gets an image deserialized from provided data.
///
/// - Parameters:
/// - data: The data from which an image should be deserialized.
/// - options: Options for deserialization.
/// - Returns: An image deserialized or `nil` when no valid image
/// could be deserialized.
public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
}

View File

@@ -0,0 +1,588 @@
//
// DiskStorage.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/15.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Represents a set of conception related to storage which stores a certain type of value in disk.
/// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the
/// storage. See these composed types for more information.
public enum DiskStorage {
/// Represents a storage back-end for the `DiskStorage`. The value is serialized to data
/// and stored as file in the file system under a specified location.
///
/// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value.
/// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep
/// track of a file for its expiration or size limitation.
public class Backend<T: DataTransformable> {
/// The config used for this disk storage.
public var config: Config
// The final storage URL on disk, with `name` and `cachePathBlock` considered.
public let directoryURL: URL
let metaChangingQueue: DispatchQueue
var maybeCached : Set<String>?
let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
// `false` if the storage initialized with an error. This prevents unexpected forcibly crash when creating
// storage in the default cache.
private var storageReady: Bool = true
/// Creates a disk storage with the given `DiskStorage.Config`.
///
/// - Parameter config: The config used for this disk storage.
/// - Throws: An error if the folder for storage cannot be got or created.
public convenience init(config: Config) throws {
self.init(noThrowConfig: config, creatingDirectory: false)
try prepareDirectory()
}
// If `creatingDirectory` is `false`, the directory preparation will be skipped.
// We need to call `prepareDirectory` manually after this returns.
init(noThrowConfig config: Config, creatingDirectory: Bool) {
var config = config
let creation = Creation(config)
self.directoryURL = creation.directoryURL
// Break any possible retain cycle set by outside.
config.cachePathBlock = nil
self.config = config
metaChangingQueue = DispatchQueue(label: creation.cacheName)
setupCacheChecking()
if creatingDirectory {
try? prepareDirectory()
}
}
private func setupCacheChecking() {
maybeCachedCheckingQueue.async {
do {
self.maybeCached = Set()
try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in
self.maybeCached?.insert(fileName)
}
} catch {
// Just disable the functionality if we fail to initialize it properly. This will just revert to
// the behavior which is to check file existence on disk directly.
self.maybeCached = nil
}
}
}
// Creates the storage folder.
private func prepareDirectory() throws {
let fileManager = config.fileManager
let path = directoryURL.path
guard !fileManager.fileExists(atPath: path) else { return }
do {
try fileManager.createDirectory(
atPath: path,
withIntermediateDirectories: true,
attributes: nil)
} catch {
self.storageReady = false
throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
}
}
/// Stores a value to the storage under the specified key and expiration policy.
/// - Parameters:
/// - value: The value to be stored.
/// - key: The key to which the `value` will be stored. If there is already a value under the key,
/// the old value will be overwritten by `value`.
/// - expiration: The expiration policy used by this store action.
/// - writeOptions: Data writing options used the new files.
/// - Throws: An error during converting the value to a data format or during writing it to disk.
public func store(
value: T,
forKey key: String,
expiration: StorageExpiration? = nil,
writeOptions: Data.WritingOptions = []) throws
{
guard storageReady else {
throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
}
let expiration = expiration ?? config.expiration
// The expiration indicates that already expired, no need to store.
guard !expiration.isExpired else { return }
let data: Data
do {
data = try value.toData()
} catch {
throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
}
let fileURL = cacheFileURL(forKey: key)
do {
try data.write(to: fileURL, options: writeOptions)
} catch {
throw KingfisherError.cacheError(
reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
)
}
let now = Date()
let attributes: [FileAttributeKey : Any] = [
// The last access date.
.creationDate: now.fileAttributeDate,
// The estimated expiration date.
.modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
]
do {
try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
} catch {
try? config.fileManager.removeItem(at: fileURL)
throw KingfisherError.cacheError(
reason: .cannotSetCacheFileAttribute(
filePath: fileURL.path,
attributes: attributes,
error: error
)
)
}
maybeCachedCheckingQueue.async {
self.maybeCached?.insert(fileURL.lastPathComponent)
}
}
/// Gets a value from the storage.
/// - Parameters:
/// - key: The cache key of value.
/// - extendingExpiration: The expiration policy used by this getting action.
/// - Throws: An error during converting the data to a value or during operation of disk files.
/// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
}
func value(
forKey key: String,
referenceDate: Date,
actuallyLoad: Bool,
extendingExpiration: ExpirationExtending) throws -> T?
{
guard storageReady else {
throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
}
let fileManager = config.fileManager
let fileURL = cacheFileURL(forKey: key)
let filePath = fileURL.path
let fileMaybeCached = maybeCachedCheckingQueue.sync {
return maybeCached?.contains(fileURL.lastPathComponent) ?? true
}
guard fileMaybeCached else {
return nil
}
guard fileManager.fileExists(atPath: filePath) else {
return nil
}
let meta: FileMeta
do {
let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
} catch {
throw KingfisherError.cacheError(
reason: .invalidURLResource(error: error, key: key, url: fileURL))
}
if meta.expired(referenceDate: referenceDate) {
return nil
}
if !actuallyLoad { return T.empty }
do {
let data = try Data(contentsOf: fileURL)
let obj = try T.fromData(data)
metaChangingQueue.async {
meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
}
return obj
} catch {
throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
}
}
/// Whether there is valid cached data under a given key.
/// - Parameter key: The cache key of value.
/// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
///
/// - Note:
/// This method does not actually load the data from disk, so it is faster than directly loading the cached value
/// by checking the nullability of `value(forKey:extendingExpiration:)` method.
///
public func isCached(forKey key: String) -> Bool {
return isCached(forKey: key, referenceDate: Date())
}
/// Whether there is valid cached data under a given key and a reference date.
/// - Parameters:
/// - key: The cache key of value.
/// - referenceDate: A reference date to check whether the cache is still valid.
/// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
///
/// - Note:
/// If you pass `Date()` to `referenceDate`, this method is identical to `isCached(forKey:)`. Use the
/// `referenceDate` to determine whether the cache is still valid for a future date.
public func isCached(forKey key: String, referenceDate: Date) -> Bool {
do {
let result = try value(
forKey: key,
referenceDate: referenceDate,
actuallyLoad: false,
extendingExpiration: .none
)
return result != nil
} catch {
return false
}
}
/// Removes a value from a specified key.
/// - Parameter key: The cache key of value.
/// - Throws: An error during removing the value.
public func remove(forKey key: String) throws {
let fileURL = cacheFileURL(forKey: key)
try removeFile(at: fileURL)
}
func removeFile(at url: URL) throws {
try config.fileManager.removeItem(at: url)
}
/// Removes all values in this storage.
/// - Throws: An error during removing the values.
public func removeAll() throws {
try removeAll(skipCreatingDirectory: false)
}
func removeAll(skipCreatingDirectory: Bool) throws {
try config.fileManager.removeItem(at: directoryURL)
if !skipCreatingDirectory {
try prepareDirectory()
}
}
/// The URL of the cached file with a given computed `key`.
///
/// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
/// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
///
/// - Note:
/// This method does not guarantee there is an image already cached in the returned URL. It just gives your
/// the URL that the image should be if it exists in disk storage, with the give key.
///
public func cacheFileURL(forKey key: String) -> URL {
let fileName = cacheFileName(forKey: key)
return directoryURL.appendingPathComponent(fileName, isDirectory: false)
}
func cacheFileName(forKey key: String) -> String {
if config.usesHashedFileName {
let hashedKey = key.kf.md5
if let ext = config.pathExtension {
return "\(hashedKey).\(ext)"
} else if config.autoExtAfterHashedFileName,
let ext = key.kf.ext {
return "\(hashedKey).\(ext)"
}
return hashedKey
} else {
if let ext = config.pathExtension {
return "\(key).\(ext)"
}
return key
}
}
func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
let fileManager = config.fileManager
guard let directoryEnumerator = fileManager.enumerator(
at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
{
throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
}
guard let urls = directoryEnumerator.allObjects as? [URL] else {
throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
}
return urls
}
/// Removes all expired values from this storage.
/// - Throws: A file manager error during removing the file.
/// - Returns: The URLs for removed files.
public func removeExpiredValues() throws -> [URL] {
return try removeExpiredValues(referenceDate: Date())
}
func removeExpiredValues(referenceDate: Date) throws -> [URL] {
let propertyKeys: [URLResourceKey] = [
.isDirectoryKey,
.contentModificationDateKey
]
let urls = try allFileURLs(for: propertyKeys)
let keys = Set(propertyKeys)
let expiredFiles = urls.filter { fileURL in
do {
let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
if meta.isDirectory {
return false
}
return meta.expired(referenceDate: referenceDate)
} catch {
return true
}
}
try expiredFiles.forEach { url in
try removeFile(at: url)
}
return expiredFiles
}
/// Removes all size exceeded values from this storage.
/// - Throws: A file manager error during removing the file.
/// - Returns: The URLs for removed files.
///
/// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way.
func removeSizeExceededValues() throws -> [URL] {
if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
var size = try totalSize()
if size < config.sizeLimit { return [] }
let propertyKeys: [URLResourceKey] = [
.isDirectoryKey,
.creationDateKey,
.fileSizeKey
]
let keys = Set(propertyKeys)
let urls = try allFileURLs(for: propertyKeys)
var pendings: [FileMeta] = urls.compactMap { fileURL in
guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
return nil
}
return meta
}
// Sort by last access date. Most recent file first.
pendings.sort(by: FileMeta.lastAccessDate)
var removed: [URL] = []
let target = config.sizeLimit / 2
while size > target, let meta = pendings.popLast() {
size -= UInt(meta.fileSize)
try removeFile(at: meta.url)
removed.append(meta.url)
}
return removed
}
/// Gets the total file size of the folder in bytes.
public func totalSize() throws -> UInt {
let propertyKeys: [URLResourceKey] = [.fileSizeKey]
let urls = try allFileURLs(for: propertyKeys)
let keys = Set(propertyKeys)
let totalSize: UInt = urls.reduce(0) { size, fileURL in
do {
let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
return size + UInt(meta.fileSize)
} catch {
return size
}
}
return totalSize
}
}
}
extension DiskStorage {
/// Represents the config used in a `DiskStorage`.
public struct Config {
/// The file size limit on disk of the storage in bytes. 0 means no limit.
public var sizeLimit: UInt
/// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
/// means that the disk cache would expire in one week.
public var expiration: StorageExpiration = .days(7)
/// The preferred extension of cache item. It will be appended to the file name as its extension.
/// Default is `nil`, means that the cache file does not contain a file extension.
public var pathExtension: String? = nil
/// Default is `true`, means that the cache file name will be hashed before storing.
public var usesHashedFileName = true
/// Default is `false`
/// If set to `true`, image extension will be extracted from original file name and append to
/// the hased file name and used as the cache key on disk.
public var autoExtAfterHashedFileName = false
/// Closure that takes in initial directory path and generates
/// the final disk cache path. You can use it to fully customize your cache path.
public var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
(directory, cacheName) in
return directory.appendingPathComponent(cacheName, isDirectory: true)
}
let name: String
let fileManager: FileManager
let directory: URL?
/// Creates a config value based on given parameters.
///
/// - Parameters:
/// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
/// storage. Two storages with the same `name` would share the same folder in disk, and it should
/// be prevented.
/// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
/// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
/// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
/// and append a path which is constructed by input `name`. Default is `nil`, indicates that
/// the cache directory under user domain mask will be used.
public init(
name: String,
sizeLimit: UInt,
fileManager: FileManager = .default,
directory: URL? = nil)
{
self.name = name
self.fileManager = fileManager
self.directory = directory
self.sizeLimit = sizeLimit
}
}
}
extension DiskStorage {
struct FileMeta {
let url: URL
let lastAccessDate: Date?
let estimatedExpirationDate: Date?
let isDirectory: Bool
let fileSize: Int
static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
}
init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
let meta = try fileURL.resourceValues(forKeys: resourceKeys)
self.init(
fileURL: fileURL,
lastAccessDate: meta.creationDate,
estimatedExpirationDate: meta.contentModificationDate,
isDirectory: meta.isDirectory ?? false,
fileSize: meta.fileSize ?? 0)
}
init(
fileURL: URL,
lastAccessDate: Date?,
estimatedExpirationDate: Date?,
isDirectory: Bool,
fileSize: Int)
{
self.url = fileURL
self.lastAccessDate = lastAccessDate
self.estimatedExpirationDate = estimatedExpirationDate
self.isDirectory = isDirectory
self.fileSize = fileSize
}
func expired(referenceDate: Date) -> Bool {
return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
}
func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
guard let lastAccessDate = lastAccessDate,
let lastEstimatedExpiration = estimatedExpirationDate else
{
return
}
let attributes: [FileAttributeKey : Any]
switch extendingExpiration {
case .none:
// not extending expiration time here
return
case .cacheTime:
let originalExpiration: StorageExpiration =
.seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
attributes = [
.creationDate: Date().fileAttributeDate,
.modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
]
case .expirationTime(let expirationTime):
attributes = [
.creationDate: Date().fileAttributeDate,
.modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
]
}
try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
}
}
}
extension DiskStorage {
struct Creation {
let directoryURL: URL
let cacheName: String
init(_ config: Config) {
let url: URL
if let directory = config.directory {
url = directory
} else {
url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
}
cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
directoryURL = config.cachePathBlock(url, cacheName)
}
}
}

View File

@@ -0,0 +1,118 @@
//
// RequestModifier.swift
// Kingfisher
//
// Created by Junyu Kuang on 5/28/17.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
/// `FormatIndicatedCacheSerializer` lets you indicate an image format for serialized caches.
///
/// It could serialize and deserialize PNG, JPEG and GIF images. For
/// image other than these formats, a normalized `pngRepresentation` will be used.
///
/// Example:
/// ````
/// let profileImageSize = CGSize(width: 44, height: 44)
///
/// // A round corner image.
/// let imageProcessor = RoundCornerImageProcessor(
/// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize)
///
/// let optionsInfo: KingfisherOptionsInfo = [
/// .cacheSerializer(FormatIndicatedCacheSerializer.png),
/// .processor(imageProcessor)]
///
/// A URL pointing to a JPEG image.
/// let url = URL(string: "https://example.com/image.jpg")!
///
/// // Image will be always cached as PNG format to preserve alpha channel for round rectangle.
/// // So when you load it from cache again later, it will be still round cornered.
/// // Otherwise, the corner part would be filled by white color (since JPEG does not contain an alpha channel).
/// imageView.kf.setImage(with: url, options: optionsInfo)
/// ````
public struct FormatIndicatedCacheSerializer: CacheSerializer {
/// A `FormatIndicatedCacheSerializer` which converts image from and to PNG format. If the image cannot be
/// represented by PNG format, it will fallback to its real format which is determined by `original` data.
public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil)
/// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be
/// represented by JPEG format, it will fallback to its real format which is determined by `original` data.
/// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality,
/// use `jpeg(compressionQuality:)`.
public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0)
/// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format with a settable compression
/// quality. If the image cannot be represented by JPEG format, it will fallback to its real format which is
/// determined by `original` data.
/// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer {
return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality)
}
/// A `FormatIndicatedCacheSerializer` which converts image from and to GIF format. If the image cannot be
/// represented by GIF format, it will fallback to its real format which is determined by `original` data.
public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil)
/// The indicated image format.
private let imageFormat: ImageFormat
/// The compression quality used for loss image format (like JPEG).
private let jpegCompressionQuality: CGFloat?
/// Creates data which represents the given `image` under a format.
public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? {
func imageData(withFormat imageFormat: ImageFormat) -> Data? {
return autoreleasepool { () -> Data? in
switch imageFormat {
case .PNG: return image.kf.pngRepresentation()
case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0)
case .GIF: return image.kf.gifRepresentation()
case .unknown: return nil
}
}
}
// generate data with indicated image format
if let data = imageData(withFormat: imageFormat) {
return data
}
let originalFormat = original?.kf.imageFormat ?? .unknown
// generate data with original image's format
if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) {
return data
}
return original ?? image.kf.normalized.kf.pngRepresentation()
}
/// Same implementation as `DefaultCacheSerializer`.
public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
}

View File

@@ -0,0 +1,882 @@
//
// ImageCache.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension Notification.Name {
/// This notification will be sent when the disk cache got cleaned either there are cached files expired or the
/// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger
/// this notification.
///
/// The `object` of this notification is the `ImageCache` object which sends the notification.
/// A list of removed hashes (files) could be retrieved by accessing the array under
/// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received.
/// By checking the array, you could know the hash codes of files are removed.
public static let KingfisherDidCleanDiskCache =
Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache")
}
/// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
/// Cache type of a cached image.
/// - none: The image is not cached yet when retrieving it.
/// - memory: The image is cached in memory.
/// - disk: The image is cached in disk.
public enum CacheType {
/// The image is not cached yet when retrieving it.
case none
/// The image is cached in memory.
case memory
/// The image is cached in disk.
case disk
/// Whether the cache type represents the image is already cached or not.
public var cached: Bool {
switch self {
case .memory, .disk: return true
case .none: return false
}
}
}
/// Represents the caching operation result.
public struct CacheStoreResult {
/// The cache result for memory cache. Caching an image to memory will never fail.
public let memoryCacheResult: Result<(), Never>
/// The cache result for disk cache. If an error happens during caching operation,
/// you can get it from `.failure` case of this `diskCacheResult`.
public let diskCacheResult: Result<(), KingfisherError>
}
extension KFCrossPlatformImage: CacheCostCalculable {
/// Cost of an image
public var cacheCost: Int { return kf.cost }
}
extension Data: DataTransformable {
public func toData() throws -> Data {
return self
}
public static func fromData(_ data: Data) throws -> Data {
return data
}
public static let empty = Data()
}
/// Represents the getting image operation from the cache.
///
/// - disk: The image can be retrieved from disk cache.
/// - memory: The image can be retrieved memory cache.
/// - none: The image does not exist in the cache.
public enum ImageCacheResult {
/// The image can be retrieved from disk cache.
case disk(KFCrossPlatformImage)
/// The image can be retrieved memory cache.
case memory(KFCrossPlatformImage)
/// The image does not exist in the cache.
case none
/// Extracts the image from cache result. It returns the associated `Image` value for
/// `.disk` and `.memory` case. For `.none` case, `nil` is returned.
public var image: KFCrossPlatformImage? {
switch self {
case .disk(let image): return image
case .memory(let image): return image
case .none: return nil
}
}
/// Returns the corresponding `CacheType` value based on the result type of `self`.
public var cacheType: CacheType {
switch self {
case .disk: return .disk
case .memory: return .memory
case .none: return .none
}
}
}
/// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`.
/// `ImageCache` is a high level abstract for storing an image as well as its data to memory and disk, and
/// retrieving them back.
///
/// 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 its storages as your need. This class also provide an interface for you to set
/// the memory and disk storage config.
open class ImageCache {
// MARK: Singleton
/// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no
/// other cache specified. The `name` of this default cache is "default", and you should not use this name
/// for any of your customize cache.
public static let `default` = ImageCache(name: "default")
// MARK: Public Properties
/// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a
/// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set
/// the storage `config` and its properties.
public let memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>
/// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a
/// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set
/// the storage `config` and its properties.
public let diskStorage: DiskStorage.Backend<Data>
private let ioQueue: DispatchQueue
/// Closure that defines the disk cache path from a given path and cacheName.
public typealias DiskCachePathClosure = (URL, String) -> URL
// MARK: Initializers
/// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`.
///
/// - Parameters:
/// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache.
/// - diskStorage: The `DiskStorage.Backend` object to use in the image cache.
public init(
memoryStorage: MemoryStorage.Backend<KFCrossPlatformImage>,
diskStorage: DiskStorage.Backend<Data>)
{
self.memoryStorage = memoryStorage
self.diskStorage = diskStorage
let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)"
ioQueue = DispatchQueue(label: ioQueueName)
let notifications: [(Notification.Name, Selector)]
#if !os(macOS) && !os(watchOS)
notifications = [
(UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
(UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
(UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
]
#elseif os(macOS)
notifications = [
(NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)),
]
#else
notifications = []
#endif
notifications.forEach {
NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil)
}
}
/// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created
/// with a default config based on the `name`.
///
/// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue.
/// You should not use the same `name` for different caches, otherwise, the disk storage would
/// be conflicting to each other. The `name` should not be an empty string.
public convenience init(name: String) {
self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil)
}
/// Creates an `ImageCache` with a given `name`, cache directory `path`
/// and a closure to modify the cache directory.
///
/// - Parameters:
/// - name: The name of cache object. It is used to setup disk cache directories and IO queue.
/// You should not use the same `name` for different caches, otherwise, the disk storage would
/// be conflicting to each other.
/// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the
/// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache
/// directory under user domain mask will be used.
/// - diskCachePathClosure: Closure that takes in an optional initial path string and generates
/// the final disk cache path. You could use it to fully customize your cache path.
/// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given
/// path.
public convenience init(
name: String,
cacheDirectoryURL: URL?,
diskCachePathClosure: DiskCachePathClosure? = nil
) throws
{
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let memoryStorage = ImageCache.createMemoryStorage()
let config = ImageCache.createConfig(
name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
)
let diskStorage = try DiskStorage.Backend<Data>(config: config)
self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
}
convenience init(
noThrowName name: String,
cacheDirectoryURL: URL?,
diskCachePathClosure: DiskCachePathClosure?
)
{
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let memoryStorage = ImageCache.createMemoryStorage()
let config = ImageCache.createConfig(
name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure
)
let diskStorage = DiskStorage.Backend<Data>(noThrowConfig: config, creatingDirectory: true)
self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
}
private static func createMemoryStorage() -> MemoryStorage.Backend<KFCrossPlatformImage> {
let totalMemory = ProcessInfo.processInfo.physicalMemory
let costLimit = totalMemory / 4
let memoryStorage = MemoryStorage.Backend<KFCrossPlatformImage>(config:
.init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
return memoryStorage
}
private static func createConfig(
name: String,
cacheDirectoryURL: URL?,
diskCachePathClosure: DiskCachePathClosure? = nil
) -> DiskStorage.Config
{
var diskConfig = DiskStorage.Config(
name: name,
sizeLimit: 0,
directory: cacheDirectoryURL
)
if let closure = diskCachePathClosure {
diskConfig.cachePathBlock = closure
}
return diskConfig
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Storing Images
open func store(_ image: KFCrossPlatformImage,
original: Data? = nil,
forKey key: String,
options: KingfisherParsedOptionsInfo,
toDisk: Bool = true,
completionHandler: ((CacheStoreResult) -> Void)? = nil)
{
let identifier = options.processor.identifier
let callbackQueue = options.callbackQueue
let computedKey = key.computedKey(with: identifier)
// Memory storage should not throw.
memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration)
guard toDisk else {
if let completionHandler = completionHandler {
let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
callbackQueue.execute { completionHandler(result) }
}
return
}
ioQueue.async {
let serializer = options.cacheSerializer
if let data = serializer.data(with: image, original: original) {
self.syncStoreToDisk(
data,
forKey: key,
processorIdentifier: identifier,
callbackQueue: callbackQueue,
expiration: options.diskCacheExpiration,
writeOptions: options.diskStoreWriteOptions,
completionHandler: completionHandler)
} else {
guard let completionHandler = completionHandler else { return }
let diskError = KingfisherError.cacheError(
reason: .cannotSerializeImage(image: image, original: original, serializer: serializer))
let result = CacheStoreResult(
memoryCacheResult: .success(()),
diskCacheResult: .failure(diskError))
callbackQueue.execute { completionHandler(result) }
}
}
}
/// Stores an image to the cache.
///
/// - Parameters:
/// - image: The image to be stored.
/// - original: The original data of the image. This value will be forwarded to the provided `serializer` for
/// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to
/// data for caching in disk, it checks the image format based on `original` data to determine in
/// which image format should be used. For other types of `serializer`, it depends on their
/// implementation detail on how to use this original data.
/// - key: The key used for caching the image.
/// - identifier: The identifier of processor being used for caching. If you are using a processor for the
/// image, pass the identifier of processor to this parameter.
/// - serializer: The `CacheSerializer`
/// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory.
/// Otherwise, it is cached in both memory storage and disk storage. Default is `true`.
/// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case
/// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the
/// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called
/// from an internal file IO queue. To change this behavior, specify another `CallbackQueue`
/// value.
/// - completionHandler: A closure which is invoked when the cache operation finishes.
open func store(_ image: KFCrossPlatformImage,
original: Data? = nil,
forKey key: String,
processorIdentifier identifier: String = "",
cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
toDisk: Bool = true,
callbackQueue: CallbackQueue = .untouch,
completionHandler: ((CacheStoreResult) -> Void)? = nil)
{
struct TempProcessor: ImageProcessor {
let identifier: String
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
return nil
}
}
let options = KingfisherParsedOptionsInfo([
.processor(TempProcessor(identifier: identifier)),
.cacheSerializer(serializer),
.callbackQueue(callbackQueue)
])
store(image, original: original, forKey: key, options: options,
toDisk: toDisk, completionHandler: completionHandler)
}
open func storeToDisk(
_ data: Data,
forKey key: String,
processorIdentifier identifier: String = "",
expiration: StorageExpiration? = nil,
callbackQueue: CallbackQueue = .untouch,
completionHandler: ((CacheStoreResult) -> Void)? = nil)
{
ioQueue.async {
self.syncStoreToDisk(
data,
forKey: key,
processorIdentifier: identifier,
callbackQueue: callbackQueue,
expiration: expiration,
completionHandler: completionHandler)
}
}
private func syncStoreToDisk(
_ data: Data,
forKey key: String,
processorIdentifier identifier: String = "",
callbackQueue: CallbackQueue = .untouch,
expiration: StorageExpiration? = nil,
writeOptions: Data.WritingOptions = [],
completionHandler: ((CacheStoreResult) -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
let result: CacheStoreResult
do {
try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration, writeOptions: writeOptions)
result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(()))
} catch {
let diskError: KingfisherError
if let error = error as? KingfisherError {
diskError = error
} else {
diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error))
}
result = CacheStoreResult(
memoryCacheResult: .success(()),
diskCacheResult: .failure(diskError)
)
}
if let completionHandler = completionHandler {
callbackQueue.execute { completionHandler(result) }
}
}
// MARK: Removing Images
/// Removes the image for the given key from the cache.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - identifier: The identifier of processor being used for caching. If you are using a processor for the
/// image, pass the identifier of processor to this parameter.
/// - fromMemory: Whether this image should be removed from memory storage or not.
/// If `false`, the image won't be removed from the memory storage. Default is `true`.
/// - fromDisk: Whether this image should be removed from disk storage or not.
/// If `false`, the image won't be removed from the disk storage. Default is `true`.
/// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
/// - completionHandler: A closure which is invoked when the cache removing operation finishes.
open func removeImage(forKey key: String,
processorIdentifier identifier: String = "",
fromMemory: Bool = true,
fromDisk: Bool = true,
callbackQueue: CallbackQueue = .untouch,
completionHandler: (() -> Void)? = nil)
{
let computedKey = key.computedKey(with: identifier)
if fromMemory {
memoryStorage.remove(forKey: computedKey)
}
if fromDisk {
ioQueue.async{
try? self.diskStorage.remove(forKey: computedKey)
if let completionHandler = completionHandler {
callbackQueue.execute { completionHandler() }
}
}
} else {
if let completionHandler = completionHandler {
callbackQueue.execute { completionHandler() }
}
}
}
// MARK: Getting Images
/// Gets an image for a given key from the cache, either from memory storage or disk storage.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image.
/// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`.
/// - completionHandler: A closure which is invoked when the image getting operation finishes. If the
/// image retrieving operation finishes without problem, an `ImageCacheResult` value
/// will be sent to this closure as result. Otherwise, a `KingfisherError` result
/// with detail failing reason will be sent.
open func retrieveImage(
forKey key: String,
options: KingfisherParsedOptionsInfo,
callbackQueue: CallbackQueue = .mainCurrentOrAsync,
completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
{
// No completion handler. No need to start working and early return.
guard let completionHandler = completionHandler else { return }
// Try to check the image from memory cache first.
if let image = retrieveImageInMemoryCache(forKey: key, options: options) {
callbackQueue.execute { completionHandler(.success(.memory(image))) }
} else if options.fromMemoryCacheOrRefresh {
callbackQueue.execute { completionHandler(.success(.none)) }
} else {
// Begin to disk search.
self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) {
result in
switch result {
case .success(let image):
guard let image = image else {
// No image found in disk storage.
callbackQueue.execute { completionHandler(.success(.none)) }
return
}
// Cache the disk image to memory.
// We are passing `false` to `toDisk`, the memory cache does not change
// callback queue, we can call `completionHandler` without another dispatch.
var cacheOptions = options
cacheOptions.callbackQueue = .untouch
self.store(
image,
forKey: key,
options: cacheOptions,
toDisk: false)
{
_ in
callbackQueue.execute { completionHandler(.success(.disk(image))) }
}
case .failure(let error):
callbackQueue.execute { completionHandler(.failure(error)) }
}
}
}
}
/// Gets an image for a given key from the cache, either from memory storage or disk storage.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
/// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`.
/// - completionHandler: A closure which is invoked when the image getting operation finishes. If the
/// image retrieving operation finishes without problem, an `ImageCacheResult` value
/// will be sent to this closure as result. Otherwise, a `KingfisherError` result
/// with detail failing reason will be sent.
///
/// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override
/// the version receives `KingfisherParsedOptionsInfo` instead.
open func retrieveImage(forKey key: String,
options: KingfisherOptionsInfo? = nil,
callbackQueue: CallbackQueue = .mainCurrentOrAsync,
completionHandler: ((Result<ImageCacheResult, KingfisherError>) -> Void)?)
{
retrieveImage(
forKey: key,
options: KingfisherParsedOptionsInfo(options),
callbackQueue: callbackQueue,
completionHandler: completionHandler)
}
/// Gets an image for a given key from the memory storage.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image.
/// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
/// has already expired, `nil` is returned.
open func retrieveImageInMemoryCache(
forKey key: String,
options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?
{
let computedKey = key.computedKey(with: options.processor.identifier)
return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration)
}
/// Gets an image for a given key from the memory storage.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
/// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or
/// has already expired, `nil` is returned.
///
/// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override
/// the version receives `KingfisherParsedOptionsInfo` instead.
open func retrieveImageInMemoryCache(
forKey key: String,
options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage?
{
return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
}
func retrieveImageInDiskCache(
forKey key: String,
options: KingfisherParsedOptionsInfo,
callbackQueue: CallbackQueue = .untouch,
completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
{
let computedKey = key.computedKey(with: options.processor.identifier)
let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
loadingQueue.execute {
do {
var image: KFCrossPlatformImage? = nil
if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) {
image = options.cacheSerializer.image(with: data, options: options)
}
if options.backgroundDecode {
image = image?.kf.decoded(scale: options.scaleFactor)
}
callbackQueue.execute { completionHandler(.success(image)) }
} catch let error as KingfisherError {
callbackQueue.execute { completionHandler(.failure(error)) }
} catch {
assertionFailure("The internal thrown error should be a `KingfisherError`.")
}
}
}
/// Gets an image for a given key from the disk storage.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image.
/// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`.
/// - completionHandler: A closure which is invoked when the operation finishes.
open func retrieveImageInDiskCache(
forKey key: String,
options: KingfisherOptionsInfo? = nil,
callbackQueue: CallbackQueue = .untouch,
completionHandler: @escaping (Result<KFCrossPlatformImage?, KingfisherError>) -> Void)
{
retrieveImageInDiskCache(
forKey: key,
options: KingfisherParsedOptionsInfo(options),
callbackQueue: callbackQueue,
completionHandler: completionHandler)
}
// MARK: Cleaning
/// Clears the memory & disk storage of this cache. This is an async operation.
///
/// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
/// This `handler` will be called from the main queue.
public func clearCache(completion handler: (() -> Void)? = nil) {
clearMemoryCache()
clearDiskCache(completion: handler)
}
/// Clears the memory storage of this cache.
@objc public func clearMemoryCache() {
memoryStorage.removeAll()
}
/// Clears the disk storage of this cache. This is an async operation.
///
/// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
/// This `handler` will be called from the main queue.
open func clearDiskCache(completion handler: (() -> Void)? = nil) {
ioQueue.async {
do {
try self.diskStorage.removeAll()
} catch _ { }
if let handler = handler {
DispatchQueue.main.async { handler() }
}
}
}
/// Clears the expired images from memory & disk storage. This is an async operation.
open func cleanExpiredCache(completion handler: (() -> Void)? = nil) {
cleanExpiredMemoryCache()
cleanExpiredDiskCache(completion: handler)
}
/// Clears the expired images from disk storage.
open func cleanExpiredMemoryCache() {
memoryStorage.removeExpired()
}
/// Clears the expired images from disk storage. This is an async operation.
@objc func cleanExpiredDiskCache() {
cleanExpiredDiskCache(completion: nil)
}
/// Clears the expired images from disk storage. This is an async operation.
///
/// - Parameter handler: A closure which is invoked when the cache clearing operation finishes.
/// This `handler` will be called from the main queue.
open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) {
ioQueue.async {
do {
var removed: [URL] = []
let removedExpired = try self.diskStorage.removeExpiredValues()
removed.append(contentsOf: removedExpired)
let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues()
removed.append(contentsOf: removedSizeExceeded)
if !removed.isEmpty {
DispatchQueue.main.async {
let cleanedHashes = removed.map { $0.lastPathComponent }
NotificationCenter.default.post(
name: .KingfisherDidCleanDiskCache,
object: self,
userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
}
if let handler = handler {
DispatchQueue.main.async { handler() }
}
} catch {}
}
}
#if !os(macOS) && !os(watchOS)
/// Clears the expired images from disk storage when app is in background. This is an async operation.
/// In most cases, you should not call this method explicitly.
/// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
@objc public func backgroundCleanExpiredDiskCache() {
// if 'sharedApplication()' is unavailable, then return
guard let sharedApplication = KingfisherWrapper<UIApplication>.shared else { return }
func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
sharedApplication.endBackgroundTask(task)
task = UIBackgroundTaskIdentifier.invalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = sharedApplication.beginBackgroundTask {
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCache {
endBackgroundTask(&backgroundTask!)
}
}
#endif
// MARK: Image Cache State
/// Returns the cache type for a given `key` and `identifier` combination.
/// This method is used for checking whether an image is cached in current cache.
/// It also provides information on which kind of cache can it be found in the return value.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - identifier: Processor identifier which used for this image. Default is the `identifier` of
/// `DefaultImageProcessor.default`.
/// - Returns: A `CacheType` instance which indicates the cache status.
/// `.none` means the image is not in cache or it is already expired.
open func imageCachedType(
forKey key: String,
processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType
{
let computedKey = key.computedKey(with: identifier)
if memoryStorage.isCached(forKey: computedKey) { return .memory }
if diskStorage.isCached(forKey: computedKey) { return .disk }
return .none
}
/// Returns whether the file exists in cache for a given `key` and `identifier` combination.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - identifier: Processor identifier which used for this image. Default is the `identifier` of
/// `DefaultImageProcessor.default`.
/// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination.
///
/// - Note:
/// The return value does not contain information about from which kind of storage the cache matches.
/// To get the information about cache type according `CacheType`,
/// use `imageCachedType(forKey:processorIdentifier:)` instead.
public func isCached(
forKey key: String,
processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool
{
return imageCachedType(forKey: key, processorIdentifier: identifier).cached
}
/// Gets the hash used as cache file name for the key.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - identifier: Processor identifier which used for this image. Default is the `identifier` of
/// `DefaultImageProcessor.default`.
/// - Returns: The hash which is used as the cache file name.
///
/// - Note:
/// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value
/// returned by this method as the cache file name. You can use this value to check and match cache file
/// if you need.
open func hash(
forKey key: String,
processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
{
let computedKey = key.computedKey(with: identifier)
return diskStorage.cacheFileName(forKey: computedKey)
}
/// Calculates the size taken by the disk storage.
/// It is the total file size of all cached files in the `diskStorage` on disk in bytes.
///
/// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue.
open func calculateDiskStorageSize(completion handler: @escaping ((Result<UInt, KingfisherError>) -> Void)) {
ioQueue.async {
do {
let size = try self.diskStorage.totalSize()
DispatchQueue.main.async { handler(.success(size)) }
} catch let error as KingfisherError {
DispatchQueue.main.async { handler(.failure(error)) }
} catch {
assertionFailure("The internal thrown error should be a `KingfisherError`.")
}
}
}
#if swift(>=5.5)
#if canImport(_Concurrency)
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var diskStorageSize: UInt {
get async throws {
try await withCheckedThrowingContinuation { continuation in
calculateDiskStorageSize { result in
continuation.resume(with: result)
}
}
}
}
#endif
#endif
/// Gets the cache path for the key.
/// It is useful for projects with web view or anyone that needs access to the local file path.
///
/// i.e. Replacing the `<img src='path_for_key'>` tag in your HTML.
///
/// - Parameters:
/// - key: The key used for caching the image.
/// - identifier: Processor identifier which used for this image. Default is the `identifier` of
/// `DefaultImageProcessor.default`.
/// - Returns: The disk path of cached image under the given `key` and `identifier`.
///
/// - Note:
/// This method does not guarantee there is an image already cached in the returned path. It just gives your
/// the path that the image should be, if it exists in disk storage.
///
/// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk.
open func cachePath(
forKey key: String,
processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String
{
let computedKey = key.computedKey(with: identifier)
return diskStorage.cacheFileURL(forKey: computedKey).path
}
}
#if !os(macOS) && !os(watchOS)
// MARK: - For App Extensions
extension UIApplication: KingfisherCompatible { }
extension KingfisherWrapper where Base: UIApplication {
public static var shared: UIApplication? {
let selector = NSSelectorFromString("sharedApplication")
guard Base.responds(to: selector) else { return nil }
return Base.perform(selector).takeUnretainedValue() as? UIApplication
}
}
#endif
extension String {
func computedKey(with identifier: String) -> String {
if identifier.isEmpty {
return self
} else {
return appending("@\(identifier)")
}
}
}

View File

@@ -0,0 +1,283 @@
//
// MemoryStorage.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/15.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Represents a set of conception related to storage which stores a certain type of value in memory.
/// This is a namespace for the memory storage types. A `Backend` with a certain `Config` will be used to describe the
/// storage. See these composed types for more information.
public enum MemoryStorage {
/// Represents a storage which stores a certain type of value in memory. It provides fast access,
/// but limited storing size. The stored value type needs to conform to `CacheCostCalculable`,
/// and its `cacheCost` will be used to determine the cost of size for the cache item.
///
/// You can config a `MemoryStorage.Backend` in its initializer by passing a `MemoryStorage.Config` value.
/// or modifying the `config` property after it being created. The backend of `MemoryStorage` has
/// upper limitation on cost size in memory and item count. All items in the storage has an expiration
/// date. When retrieved, if the target item is already expired, it will be recognized as it does not
/// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired
/// items from memory.
public class Backend<T: CacheCostCalculable> {
let storage = NSCache<NSString, StorageObject<T>>()
// Keys trackes the objects once inside the storage. For object removing triggered by user, the corresponding
// key would be also removed. However, for the object removing triggered by cache rule/policy of system, the
// key will be remained there until next `removeExpired` happens.
//
// Breaking the strict tracking could save additional locking behaviors.
// See https://github.com/onevcat/Kingfisher/issues/1233
var keys = Set<String>()
private var cleanTimer: Timer? = nil
private let lock = NSLock()
/// The config used in this storage. It is a value you can set and
/// use to config the storage in air.
public var config: Config {
didSet {
storage.totalCostLimit = config.totalCostLimit
storage.countLimit = config.countLimit
}
}
/// Creates a `MemoryStorage` with a given `config`.
///
/// - Parameter config: The config used to create the storage. It determines the max size limitation,
/// default expiration setting and more.
public init(config: Config) {
self.config = config
storage.totalCostLimit = config.totalCostLimit
storage.countLimit = config.countLimit
cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
guard let self = self else { return }
self.removeExpired()
}
}
/// Removes the expired values from the storage.
public func removeExpired() {
lock.lock()
defer { lock.unlock() }
for key in keys {
let nsKey = key as NSString
guard let object = storage.object(forKey: nsKey) else {
// This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule.
// We didn't remove the key yet until now, since we do not want to introduce additional lock.
// See https://github.com/onevcat/Kingfisher/issues/1233
keys.remove(key)
continue
}
if object.isExpired {
storage.removeObject(forKey: nsKey)
keys.remove(key)
}
}
}
/// Stores a value to the storage under the specified key and expiration policy.
/// - Parameters:
/// - value: The value to be stored.
/// - key: The key to which the `value` will be stored.
/// - expiration: The expiration policy used by this store action.
/// - Throws: No error will
public func store(
value: T,
forKey key: String,
expiration: StorageExpiration? = nil)
{
storeNoThrow(value: value, forKey: key, expiration: expiration)
}
// The no throw version for storing value in cache. Kingfisher knows the detail so it
// could use this version to make syntax simpler internally.
func storeNoThrow(
value: T,
forKey key: String,
expiration: StorageExpiration? = nil)
{
lock.lock()
defer { lock.unlock() }
let expiration = expiration ?? config.expiration
// The expiration indicates that already expired, no need to store.
guard !expiration.isExpired else { return }
let object: StorageObject<T>
if config.keepWhenEnteringBackground {
object = BackgroundKeepingStorageObject(value, expiration: expiration)
} else {
object = StorageObject(value, expiration: expiration)
}
storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
keys.insert(key)
}
/// Gets a value from the storage.
///
/// - Parameters:
/// - key: The cache key of value.
/// - extendingExpiration: The expiration policy used by this getting action.
/// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
guard let object = storage.object(forKey: key as NSString) else {
return nil
}
if object.isExpired {
return nil
}
object.extendExpiration(extendingExpiration)
return object.value
}
/// Whether there is valid cached data under a given key.
/// - Parameter key: The cache key of value.
/// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
public func isCached(forKey key: String) -> Bool {
guard let _ = value(forKey: key, extendingExpiration: .none) else {
return false
}
return true
}
/// Removes a value from a specified key.
/// - Parameter key: The cache key of value.
public func remove(forKey key: String) {
lock.lock()
defer { lock.unlock() }
storage.removeObject(forKey: key as NSString)
keys.remove(key)
}
/// Removes all values in this storage.
public func removeAll() {
lock.lock()
defer { lock.unlock() }
storage.removeAllObjects()
keys.removeAll()
}
}
}
extension MemoryStorage {
/// Represents the config used in a `MemoryStorage`.
public struct Config {
/// Total cost limit of the storage in bytes.
public var totalCostLimit: Int
/// The item count limit of the memory storage.
public var countLimit: Int = .max
/// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
/// means that the memory cache would expire in 5 minutes.
public var expiration: StorageExpiration = .seconds(300)
/// The time interval between the storage do clean work for swiping expired items.
public var cleanInterval: TimeInterval
/// Whether the newly added items to memory cache should be purged when the app goes to background.
///
/// By default, the cached items in memory will be purged as soon as the app goes to background to ensure
/// least memory footprint. Enabling this would prevent this behavior and keep the items alive in cache even
/// when your app is not in foreground anymore.
///
/// Default is `false`. After setting `true`, only the newly added cache objects are affected. Existing
/// objects which are already in the cache while this value was `false` will be still be purged when entering
/// background.
public var keepWhenEnteringBackground: Bool = false
/// Creates a config from a given `totalCostLimit` value.
///
/// - Parameters:
/// - totalCostLimit: Total cost limit of the storage in bytes.
/// - cleanInterval: The time interval between the storage do clean work for swiping expired items.
/// Default is 120, means the auto eviction happens once per two minutes.
///
/// - Note:
/// Other members of `MemoryStorage.Config` will use their default values when created.
public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
self.totalCostLimit = totalCostLimit
self.cleanInterval = cleanInterval
}
}
}
extension MemoryStorage {
class BackgroundKeepingStorageObject<T>: StorageObject<T>, NSDiscardableContent {
var accessing = true
func beginContentAccess() -> Bool {
if value != nil {
accessing = true
} else {
accessing = false
}
return accessing
}
func endContentAccess() {
accessing = false
}
func discardContentIfPossible() {
value = nil
}
func isContentDiscarded() -> Bool {
return value == nil
}
}
class StorageObject<T> {
var value: T?
let expiration: StorageExpiration
private(set) var estimatedExpiration: Date
init(_ value: T, expiration: StorageExpiration) {
self.value = value
self.expiration = expiration
self.estimatedExpiration = expiration.estimatedExpirationSinceNow
}
func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
switch extendingExpiration {
case .none:
return
case .cacheTime:
self.estimatedExpiration = expiration.estimatedExpirationSinceNow
case .expirationTime(let expirationTime):
self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
}
}
var isExpired: Bool {
return estimatedExpiration.isPast
}
}
}

View File

@@ -0,0 +1,110 @@
//
// Storage.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/15.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Constants for some time intervals
struct TimeConstants {
static let secondsInOneDay = 86_400
}
/// Represents the expiration strategy used in storage.
///
/// - never: The item never expires.
/// - seconds: The item expires after a time duration of given seconds from now.
/// - days: The item expires after a time duration of given days from now.
/// - date: The item expires after a given date.
public enum StorageExpiration {
/// The item never expires.
case never
/// The item expires after a time duration of given seconds from now.
case seconds(TimeInterval)
/// The item expires after a time duration of given days from now.
case days(Int)
/// The item expires after a given date.
case date(Date)
/// Indicates the item is already expired. Use this to skip cache.
case expired
func estimatedExpirationSince(_ date: Date) -> Date {
switch self {
case .never: return .distantFuture
case .seconds(let seconds):
return date.addingTimeInterval(seconds)
case .days(let days):
let duration: TimeInterval = TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
return date.addingTimeInterval(duration)
case .date(let ref):
return ref
case .expired:
return .distantPast
}
}
var estimatedExpirationSinceNow: Date {
return estimatedExpirationSince(Date())
}
var isExpired: Bool {
return timeInterval <= 0
}
var timeInterval: TimeInterval {
switch self {
case .never: return .infinity
case .seconds(let seconds): return seconds
case .days(let days): return TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
case .date(let ref): return ref.timeIntervalSinceNow
case .expired: return -(.infinity)
}
}
}
/// Represents the expiration extending strategy used in storage to after access.
///
/// - none: The item expires after the original time, without extending after access.
/// - cacheTime: The item expiration extends by the original cache time after each access.
/// - expirationTime: The item expiration extends by the provided time after each access.
public enum ExpirationExtending {
/// The item expires after the original time, without extending after access.
case none
/// The item expiration extends by the original cache time after each access.
case cacheTime
/// The item expiration extends by the provided time after each access.
case expirationTime(_ expiration: StorageExpiration)
}
/// Represents types which cost in memory can be calculated.
public protocol CacheCostCalculable {
var cacheCost: Int { get }
}
/// Represents types which can be converted to and from data.
public protocol DataTransformable {
func toData() throws -> Data
static func fromData(_ data: Data) throws -> Self
static var empty: Self { get }
}