+
+Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work with remote images in your next app.
+
+## Features
+
+- [x] Asynchronous image downloading and caching.
+- [x] Loading image from either `URLSession`-based networking or local provided data.
+- [x] Useful image processors and filters provided.
+- [x] Multiple-layer hybrid cache for both memory and disk.
+- [x] Fine control on cache behavior. Customizable expiration date and size limit.
+- [x] Cancelable downloading and auto-reusing previous downloaded content to improve performance.
+- [x] Independent components. Use the downloader, caching system and image processors separately as you need.
+- [x] Prefetching images and showing them from cache to boost your app.
+- [x] View extensions for `UIImageView`, `NSImageView`, `NSButton` and `UIButton` to directly set an image from a URL.
+- [x] Built-in transition animation when setting images.
+- [x] Customizable placeholder and indicator while loading images.
+- [x] Extensible image processing and image format easily.
+
+### Kingfisher 101
+
+The simplest use-case is setting an image to an image view with the `UIImageView` extension:
+
+```swift
+let url = URL(string: "https://example.com/image.png")
+imageView.kf.setImage(with: url)
+```
+
+Kingfisher will download the image from `url`, send it to both memory cache and disk cache, and display it in `imageView`. When you set with the same URL later, the image will be retrieved from cache and shown immediately.
+
+### A More Advanced Example
+
+With the powerful options, you can do hard tasks with Kingfisher in a simple way. For example, the code below:
+
+1. Downloads a high-resolution image.
+2. Downsamples it to match the image view size.
+3. Makes it round cornered with a given radius.
+4. Shows a system indicator and a placeholder image while downloading.
+5. When prepared, it animates the small thumbnail image with a "fade in" effect.
+6. The original large image is also cached to disk for later use, to get rid of downloading it again in a detail view.
+7. A console log is printed when the task finishes, either for success or failure.
+
+```swift
+let url = URL(string: "https://example.com/high_resolution_image.png")
+let processor = DownsamplingImageProcessor(size: imageView.size)
+ >> RoundCornerImageProcessor(cornerRadius: 20)
+imageView.kf.indicatorType = .activity
+imageView.kf.setImage(
+ with: url,
+ placeholder: UIImage(named: "placeholderImage"),
+ options: [
+ .processor(processor),
+ .scaleFactor(UIScreen.main.scale),
+ .transition(.fade(1)),
+ .cacheOriginalImage
+ ])
+{
+ result in
+ switch result {
+ case .success(let value):
+ print("Task done for: \(value.source.url?.absoluteString ?? "")")
+ case .failure(let error):
+ print("Job failed: \(error.localizedDescription)")
+ }
+}
+```
+
+It is really a very common situation I can meet in my daily work. Think about how many lines you need to write without Kingfisher. You will fall in love with it if you give it a try!
+
+### Learn More
+
+To learn the using of Kingfisher by more examples, take a look at the [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet). There we summarized most common tasks in Kingfisher, you can get a better idea on what this framework can do. There are also some tips for performance in the same page, remember to check them too.
+
+## Requirements
+
+- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
+- Swift 4.0+
+
+[Kingfisher 5.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) - Kingfisher 5.x is NOT fully compatible with version 4.x. However, the migration is not difficult. Depending on your use cases, it may take no effect or several minutes to modify your existing code for the new version. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project.
+
+If you are using an even earlier version, see the guides below to know the steps for migrating.
+
+> - Kingfisher 4.0 Migration - Kingfisher 3.x should be source compatible to Kingfisher 4. The reason for a major update is that we need to specify the Swift version explicitly for Xcode. All deprecated methods in Kingfisher 3 has been removed, so please ensure you have no warning left before you migrate from Kingfisher 3 to Kingfisher 4. If you have any trouble in migrating, please open an issue to discuss.
+> - [Kingfisher 3.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information.
+
+## Next Steps
+
+We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there.
+
+* [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project.
+* [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher!
+* [API Reference](http://onevcat.github.io/Kingfisher/) - Lastly, please remember to read the full whenever you may need a more detailed reference.
+
+## Other
+
+### Future of Kingfisher
+
+I want to keep Kingfisher lightweight. This framework will focus on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better.
+
+### Developments and Tests
+
+Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build and with all tests green. :)
+
+### About the logo
+
+The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions?
+
+### Contact
+
+Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, just [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well.
+
+## Contributors
+
+This project exists thanks to all the people who contribute. [[Contribute]](https://github.com/onevcat/Kingfisher/blob/master/CONTRIBUTING.md).
+
+
+
+## Backers
+
+Thank you to all our backers! Your support is really important for the project and encourages us to continue. 🙏 [[Become a backer](https://opencollective.com/kingfisher#backer)]
+
+
+
+
+## Sponsors
+
+Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/kingfisher#sponsor)]
+
+
+
+
+
+
+
+
+
+
+
+
+### License
+
+Kingfisher is released under the MIT license. See LICENSE for details.
diff --git a/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift
new file mode 100644
index 0000000..ea72c72
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift
@@ -0,0 +1,113 @@
+//
+// CacheSerializer.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2016/09/02.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+/// 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: Image, 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) -> Image?
+
+ /// 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.
+ /// - Note:
+ /// This method is deprecated. Please implement the version with
+ /// `KingfisherParsedOptionsInfo` as parameter instead.
+ @available(*, deprecated,
+ message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.")
+ func image(with data: Data, options: KingfisherOptionsInfo?) -> Image?
+}
+
+extension CacheSerializer {
+ public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? {
+ return image(with: data, options: KingfisherParsedOptionsInfo(options))
+ }
+}
+
+/// 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()
+ private 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
+ /// a valid format, the `original` data will be used for cache.
+ ///
+ /// If `original` is `nil`, the input `image` will be encoded as PNG data.
+ public func data(with image: Image, original: Data?) -> Data? {
+ return image.kf.data(format: original?.kf.imageFormat ?? .unknown)
+ }
+
+ /// 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) -> Image? {
+ return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Cache/DiskStorage.swift b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift
new file mode 100644
index 0000000..d292d87
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift
@@ -0,0 +1,425 @@
+//
+// DiskStorage.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2018/10/15.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 {
+ /// 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
+
+ /// 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 init(config: Config) throws {
+
+ self.config = config
+
+ let url: URL
+ if let directory = config.directory {
+ url = directory
+ } else {
+ url = try config.fileManager.url(
+ for: .cachesDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true)
+ }
+
+ let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
+ directoryURL = config.cachePathBlock(url, cacheName)
+
+ metaChangingQueue = DispatchQueue(label: cacheName)
+
+ try prepareDirectory()
+ }
+
+ // Creates the storage folder.
+ 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 {
+ throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
+ }
+ }
+
+ func store(
+ value: T,
+ forKey key: String,
+ expiration: StorageExpiration? = nil) throws
+ {
+ 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)
+
+ let now = Date()
+ let attributes: [FileAttributeKey : Any] = [
+ // The last access date.
+ .creationDate: now.fileAttributeDate,
+ // The estimated expiration date.
+ .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
+ ]
+ config.fileManager.createFile(atPath: fileURL.path, contents: data, attributes: attributes)
+ }
+
+ func value(forKey key: String) throws -> T? {
+ return try value(forKey: key, referenceDate: Date(), actuallyLoad: true)
+ }
+
+ func value(forKey key: String, referenceDate: Date, actuallyLoad: Bool) throws -> T? {
+ let fileManager = config.fileManager
+ let fileURL = cacheFileURL(forKey: key)
+ let filePath = fileURL.path
+ guard fileManager.fileExists(atPath: filePath) else {
+ return nil
+ }
+
+ let meta: FileMeta
+ do {
+ let resourceKeys: Set = [.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) }
+ return obj
+ } catch {
+ throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
+ }
+ }
+
+ func isCached(forKey key: String) -> Bool {
+ return isCached(forKey: key, referenceDate: Date())
+ }
+
+ func isCached(forKey key: String, referenceDate: Date) -> Bool {
+ do {
+ guard let _ = try value(forKey: key, referenceDate: referenceDate, actuallyLoad: false) else {
+ return false
+ }
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ 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)
+ }
+
+ 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`.
+ ///
+ /// - 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.
+ ///
+ /// - 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.
+ public func cacheFileURL(forKey key: String) -> URL {
+ let fileName = cacheFileName(forKey: key)
+ return directoryURL.appendingPathComponent(fileName)
+ }
+
+ func cacheFileName(forKey key: String) -> String {
+ if config.usesHashedFileName {
+ let hashedKey = key.kf.md5
+ if let ext = config.pathExtension {
+ 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
+ }
+
+ func removeExpiredValues(referenceDate: Date = 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
+ }
+
+ 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
+ }
+
+ /// Get the total file size of the folder in bytes.
+ 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
+
+ let name: String
+ let fileManager: FileManager
+ let directory: URL?
+
+ var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
+ (directory, cacheName) in
+ return directory.appendingPathComponent(cacheName, isDirectory: true)
+ }
+
+ /// 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) 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) {
+ guard let lastAccessDate = lastAccessDate,
+ let lastEstimatedExpiration = estimatedExpirationDate else
+ {
+ return
+ }
+
+ let originalExpiration: StorageExpiration =
+ .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
+ let attributes: [FileAttributeKey : Any] = [
+ .creationDate: Date().fileAttributeDate,
+ .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
+ ]
+
+ try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
+ }
+ }
+}
+
diff --git a/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift
new file mode 100644
index 0000000..442b82c
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift
@@ -0,0 +1,102 @@
+//
+// RequestModifier.swift
+// Kingfisher
+//
+// Created by Junyu Kuang on 5/28/17.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+/// `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)
+
+ /// 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.
+ public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG)
+
+ /// 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)
+
+ /// The indicated image format.
+ private let imageFormat: ImageFormat
+
+ /// Creates data which represents the given `image` under a format.
+ public func data(with image: Image, original: Data?) -> Data? {
+
+ func imageData(withFormat imageFormat: ImageFormat) -> Data? {
+ switch imageFormat {
+ case .PNG: return image.kf.pngRepresentation()
+ case .JPEG: return image.kf.jpegRepresentation(compressionQuality: 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) -> Image? {
+ return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Cache/ImageCache.swift b/Pods/Kingfisher/Sources/Cache/ImageCache.swift
new file mode 100644
index 0000000..66a1874
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/ImageCache.swift
@@ -0,0 +1,839 @@
+//
+// ImageCache.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/6.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 Image: 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(Image)
+
+ /// The image can be retrieved memory cache.
+ case memory(Image)
+
+ /// 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: Image? {
+ 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 disk 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
+
+ /// 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
+
+ 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,
+ diskStorage: DiskStorage.Backend)
+ {
+ 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)
+ #if swift(>=4.2)
+ notifications = [
+ (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)),
+ (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)),
+ (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache))
+ ]
+ #else
+ notifications = [
+ (NSNotification.Name.UIApplicationDidReceiveMemoryWarning, #selector(clearMemoryCache)),
+ (NSNotification.Name.UIApplicationWillTerminate, #selector(cleanExpiredDiskCache)),
+ (NSNotification.Name.UIApplicationDidEnterBackground, #selector(backgroundCleanExpiredDiskCache))
+ ]
+ #endif
+ #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) {
+ try! self.init(name: 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 totalMemory = ProcessInfo.processInfo.physicalMemory
+ let costLimit = totalMemory / 4
+ let memoryStorage = MemoryStorage.Backend(config:
+ .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit)))
+
+ var diskConfig = DiskStorage.Config(
+ name: name,
+ sizeLimit: 0,
+ directory: cacheDirectoryURL
+ )
+ if let closure = diskCachePathClosure {
+ diskConfig.cachePathBlock = closure
+ }
+ let diskStorage = try DiskStorage.Backend(config: diskConfig)
+ diskConfig.cachePathBlock = nil
+
+ self.init(memoryStorage: memoryStorage, diskStorage: diskStorage)
+ }
+
+ deinit {
+ NotificationCenter.default.removeObserver(self)
+ }
+
+ // MARK: Storing Images
+
+ open func store(_ image: Image,
+ 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,
+ 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: Image,
+ 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) -> Image? {
+ 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,
+ completionHandler: ((CacheStoreResult) -> Void)? = nil)
+ {
+ let computedKey = key.computedKey(with: identifier)
+ let result: CacheStoreResult
+ do {
+ try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration)
+ 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 {
+ try? 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() }
+ }
+ }
+ }
+
+ func retrieveImage(forKey key: String,
+ options: KingfisherParsedOptionsInfo,
+ callbackQueue: CallbackQueue = .untouch,
+ completionHandler: ((Result) -> 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) {
+ let image = options.imageModifier?.modify(image) ?? image
+ 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
+ // The callback queue is already correct in this closure.
+ switch result {
+ case .success(let image):
+
+ guard let image = image else {
+ // No image found in disk storage.
+ completionHandler(.success(.none))
+ return
+ }
+
+ let finalImage = options.imageModifier?.modify(image) ?? image
+ // 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(
+ finalImage,
+ forKey: key,
+ options: cacheOptions,
+ toDisk: false)
+ {
+ _ in
+ completionHandler(.success(.disk(finalImage)))
+ }
+ case .failure(let error):
+ completionHandler(.failure(error))
+ }
+ }
+ }
+ }
+
+ // 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 `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 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: KingfisherOptionsInfo? = nil,
+ callbackQueue: CallbackQueue = .untouch,
+ completionHandler: ((Result) -> Void)?)
+ {
+ retrieveImage(
+ forKey: key,
+ options: KingfisherParsedOptionsInfo(options),
+ callbackQueue: callbackQueue,
+ completionHandler: completionHandler)
+ }
+
+ func retrieveImageInMemoryCache(
+ forKey key: String,
+ options: KingfisherParsedOptionsInfo) -> Image?
+ {
+ 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.
+ open func retrieveImageInMemoryCache(
+ forKey key: String,
+ options: KingfisherOptionsInfo? = nil) -> Image?
+ {
+ return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options))
+ }
+
+ func retrieveImageInDiskCache(
+ forKey key: String,
+ options: KingfisherParsedOptionsInfo,
+ callbackQueue: CallbackQueue = .untouch,
+ completionHandler: @escaping (Result) -> Void)
+ {
+ let computedKey = key.computedKey(with: options.processor.identifier)
+ let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue)
+ loadingQueue.execute {
+ do {
+ var image: Image? = nil
+ if let data = try self.diskStorage.value(forKey: computedKey) {
+ image = options.cacheSerializer.image(with: data, options: options)
+ }
+ callbackQueue.execute { completionHandler(.success(image)) }
+ } catch {
+ if let error = error as? KingfisherError {
+ callbackQueue.execute { completionHandler(.failure(error)) }
+ } else {
+ 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) -> Void)
+ {
+ retrieveImageInDiskCache(
+ forKey: key,
+ options: KingfisherParsedOptionsInfo(options),
+ callbackQueue: callbackQueue,
+ completionHandler: completionHandler)
+ }
+
+ // MARK: Cleaning
+ /// Clears the memory storage of this cache.
+ @objc public func clearMemoryCache() {
+ try? 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: (()->())? = nil) {
+ ioQueue.async {
+ do {
+ try self.diskStorage.removeAll()
+ } catch _ { }
+ if let handler = handler {
+ DispatchQueue.main.async { handler() }
+ }
+ }
+ }
+
+ /// Clears the expired images from disk storage. This is an async operation.
+ 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.shared else { return }
+
+ func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) {
+ sharedApplication.endBackgroundTask(task)
+ #if swift(>=4.2)
+ task = UIBackgroundTaskIdentifier.invalid
+ #else
+ task = UIBackgroundTaskInvalid
+ #endif
+ }
+
+ 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) -> Void)) {
+ ioQueue.async {
+ do {
+ let size = try self.diskStorage.totalSize()
+ DispatchQueue.main.async { handler(.success(size)) }
+ } catch {
+ if let error = error as? KingfisherError {
+ DispatchQueue.main.async { handler(.failure(error)) }
+ } else {
+ assertionFailure("The internal thrown error should be a `KingfisherError`.")
+ }
+
+ }
+ }
+ }
+
+ /// 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 `` 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
+ }
+}
+
+extension Dictionary {
+ func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
+ return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
+ }
+}
+
+#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)")
+ }
+ }
+}
+
+extension ImageCache {
+
+ /// 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.
+ /// - path: Location of cache URL on disk. It will be internally pass to the initializer of `DiskStorage` as the
+ /// disk cache directory.
+ /// - 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.
+ @available(*, deprecated, message: "Use `init(name:cacheDirectoryURL:diskCachePathClosure:)` instead",
+ renamed: "init(name:cacheDirectoryURL:diskCachePathClosure:)")
+ public convenience init(
+ name: String,
+ path: String?,
+ diskCachePathClosure: DiskCachePathClosure? = nil) throws
+ {
+ let directoryURL = path.flatMap { URL(string: $0) }
+ try self.init(name: name, cacheDirectoryURL: directoryURL, diskCachePathClosure: diskCachePathClosure)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift
new file mode 100644
index 0000000..214df3b
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift
@@ -0,0 +1,242 @@
+//
+// MemoryStorage.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2018/10/15.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 {
+ let storage = NSCache>()
+ var keys = Set()
+
+ var cleanTimer: Timer? = nil
+ let lock = NSLock()
+
+ let cacheDelegate = CacheDelegate>()
+
+ /// 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
+ storage.delegate = cacheDelegate
+ cacheDelegate.onObjectRemoved.delegate(on: self) { (self, obj) in
+ self.keys.remove(obj.key)
+ }
+
+ cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
+ guard let self = self else { return }
+ self.removeExpired()
+ }
+ }
+
+ func removeExpired() {
+ lock.lock()
+ defer { lock.unlock() }
+ for key in keys {
+ let nsKey = key as NSString
+ guard let object = storage.object(forKey: nsKey) else {
+ keys.remove(key)
+ continue
+ }
+ if object.estimatedExpiration.isPast {
+ storage.removeObject(forKey: nsKey)
+ keys.remove(key)
+ }
+ }
+ }
+
+ // Storing in memory will not throw. It is just for meeting protocol requirement and
+ // forwarding to no throwing method.
+ func store(
+ value: T,
+ forKey key: String,
+ expiration: StorageExpiration? = nil) throws
+ {
+ 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(value, key: key, expiration: expiration)
+ storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
+ keys.insert(key)
+ }
+
+ /// Use this when you actually access the memory cached item.
+ /// By default, this will extend the expired data for the accessed item.
+ ///
+ /// - Parameters:
+ /// - key: Cache Key
+ /// - extendingExpiration: expiration value to extend item expiration time:
+ /// * .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.
+ /// - Returns: cached object or nil
+ func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
+ guard let object = storage.object(forKey: key as NSString) else {
+ return nil
+ }
+ if object.expired {
+ return nil
+ }
+ object.extendExpiration(extendingExpiration)
+ return object.value
+ }
+
+ func isCached(forKey key: String) -> Bool {
+ guard let _ = value(forKey: key, extendingExpiration: .none) else {
+ return false
+ }
+ return true
+ }
+
+ func remove(forKey key: String) throws {
+ lock.lock()
+ defer { lock.unlock() }
+ storage.removeObject(forKey: key as NSString)
+ keys.remove(key)
+ }
+
+ func removeAll() throws {
+ lock.lock()
+ defer { lock.unlock() }
+ storage.removeAllObjects()
+ keys.removeAll()
+ }
+
+ class CacheDelegate: NSObject, NSCacheDelegate {
+ let onObjectRemoved = Delegate()
+ func cache(_ cache: NSCache, willEvictObject obj: Any) {
+ if let obj = obj as? T {
+ onObjectRemoved.call(obj)
+ }
+ }
+ }
+ }
+}
+
+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 let cleanInterval: TimeInterval
+
+ /// 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 StorageObject {
+ let value: T
+ let expiration: StorageExpiration
+ let key: String
+
+ private(set) var estimatedExpiration: Date
+
+ init(_ value: T, key: String, expiration: StorageExpiration) {
+ self.value = value
+ self.key = key
+ 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 expired: Bool {
+ return estimatedExpiration.isPast
+ }
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Cache/Storage.swift b/Pods/Kingfisher/Sources/Cache/Storage.swift
new file mode 100644
index 0000000..acd7f06
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Cache/Storage.swift
@@ -0,0 +1,108 @@
+//
+// Storage.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2018/10/15.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 secondsInOneMinute = 60
+ static let minutesInOneHour = 60
+ static let hoursInOneDay = 24
+ static let secondsInOneDay = secondsInOneMinute * minutesInOneHour * hoursInOneDay
+}
+
+/// 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): return date.addingTimeInterval(TimeInterval(TimeConstants.secondsInOneDay * days))
+ 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 * 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 }
+}
diff --git a/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift
new file mode 100644
index 0000000..85838f8
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift
@@ -0,0 +1,404 @@
+//
+// ImageView+Kingfisher.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/6.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 KingfisherWrapper where Base: ImageView {
+
+ // MARK: Setting Image
+
+ /// Sets an image to the image view with a `Source`.
+ ///
+ /// - Parameters:
+ /// - source: The `Source` object defines data information from network or a data provider.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
+ /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
+ ///
+ /// ```
+ /// // Set image from a network source.
+ /// let url = URL(string: "https://example.com/image.png")!
+ /// imageView.kf.setImage(with: .network(url))
+ ///
+ /// // Or set image from a data provider.
+ /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
+ /// imageView.kf.setImage(with: .provider(provider))
+ /// ```
+ ///
+ /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
+ /// above is equivalent to:
+ ///
+ /// ```
+ /// imageView.kf.setImage(with: url)
+ /// imageView.kf.setImage(with: provider)
+ /// ```
+ ///
+ /// Internally, this method will use `KingfisherManager` to get the source.
+ /// Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setImage(
+ with source: Source?,
+ placeholder: Placeholder? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ var mutatingSelf = self
+ guard let source = source else {
+ mutatingSelf.placeholder = placeholder
+ mutatingSelf.taskIdentifier = nil
+ completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+ return nil
+ }
+
+ var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+ let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
+ if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
+ // Always set placeholder while there is no image/placeholder yet.
+ mutatingSelf.placeholder = placeholder
+ }
+
+ let maybeIndicator = indicator
+ maybeIndicator?.startAnimatingView()
+
+ let issuedIdentifier = Source.Identifier.next()
+ mutatingSelf.taskIdentifier = issuedIdentifier
+
+ if base.shouldPreloadAllAnimation() {
+ options.preloadAllAnimationData = true
+ }
+
+ if let block = progressBlock {
+ options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+ }
+
+ if let provider = ImageProgressiveProvider(options, refresh: { image in
+ self.base.image = image
+ }) {
+ options.onDataReceived = (options.onDataReceived ?? []) + [provider]
+ }
+
+ options.onDataReceived?.forEach {
+ $0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
+ }
+
+ let task = KingfisherManager.shared.retrieveImage(
+ with: source,
+ options: options,
+ completionHandler: { result in
+ CallbackQueue.mainCurrentOrAsync.execute {
+ maybeIndicator?.stopAnimatingView()
+ guard issuedIdentifier == self.taskIdentifier else {
+ let reason: KingfisherError.ImageSettingErrorReason
+ do {
+ let value = try result.get()
+ reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+ } catch {
+ reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+ }
+ let error = KingfisherError.imageSettingError(reason: reason)
+ completionHandler?(.failure(error))
+ return
+ }
+
+ mutatingSelf.imageTask = nil
+ mutatingSelf.taskIdentifier = nil
+
+ switch result {
+ case .success(let value):
+ guard self.needsTransition(options: options, cacheType: value.cacheType) else {
+ mutatingSelf.placeholder = nil
+ self.base.image = value.image
+ completionHandler?(result)
+ return
+ }
+
+ self.makeTransition(image: value.image, transition: options.transition) {
+ completionHandler?(result)
+ }
+
+ case .failure:
+ if let image = options.onFailureImage {
+ self.base.image = image
+ }
+ completionHandler?(result)
+ }
+ }
+ }
+ )
+ mutatingSelf.imageTask = task
+ return task
+ }
+
+ /// Sets an image to the image view with a requested resource.
+ ///
+ /// - Parameters:
+ /// - resource: The `Resource` object contains information about the resource.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
+ /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
+ ///
+ /// ```
+ /// let url = URL(string: "https://example.com/image.png")!
+ /// imageView.kf.setImage(with: url)
+ /// ```
+ ///
+ /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+ /// or network. Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setImage(
+ with resource: Resource?,
+ placeholder: Placeholder? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ return setImage(
+ with: resource.map { .network($0) },
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+ /// Sets an image to the image view with a data provider.
+ ///
+ /// - Parameters:
+ /// - provider: The `ImageDataProvider` object contains information about the data.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
+ /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setImage(
+ with provider: ImageDataProvider?,
+ placeholder: Placeholder? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ return setImage(
+ with: provider.map { .provider($0) },
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+ // MARK: Cancelling Downloading Task
+
+ /// Cancels the image download task of the image view if it is running.
+ /// Nothing will happen if the downloading has already finished.
+ public func cancelDownloadTask() {
+ imageTask?.cancel()
+ }
+
+ private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
+ switch options.transition {
+ case .none:
+ return false
+ #if !os(macOS)
+ default:
+ if options.forceTransition { return true }
+ if cacheType == .none { return true }
+ return false
+ #endif
+ }
+ }
+
+ private func makeTransition(image: Image, transition: ImageTransition, done: @escaping () -> Void) {
+ #if !os(macOS)
+ // Force hiding the indicator without transition first.
+ UIView.transition(
+ with: self.base,
+ duration: 0.0,
+ options: [],
+ animations: { self.indicator?.stopAnimatingView() },
+ completion: { _ in
+ var mutatingSelf = self
+ mutatingSelf.placeholder = nil
+ UIView.transition(
+ with: self.base,
+ duration: transition.duration,
+ options: [transition.animationOptions, .allowUserInteraction],
+ animations: { transition.animations?(self.base, image) },
+ completion: { finished in
+ transition.completion?(finished)
+ done()
+ }
+ )
+ }
+ )
+ #else
+ done()
+ #endif
+ }
+}
+
+// MARK: - Associated Object
+private var taskIdentifierKey: Void?
+private var indicatorKey: Void?
+private var indicatorTypeKey: Void?
+private var placeholderKey: Void?
+private var imageTaskKey: Void?
+
+extension KingfisherWrapper where Base: ImageView {
+
+ // MARK: Properties
+ public private(set) var taskIdentifier: Source.Identifier.Value? {
+ get {
+ let box: Box? = getAssociatedObject(base, &taskIdentifierKey)
+ return box?.value
+ }
+ set {
+ let box = newValue.map { Box($0) }
+ setRetainedAssociatedObject(base, &taskIdentifierKey, box)
+ }
+ }
+
+ /// Holds which indicator type is going to be used.
+ /// Default is `.none`, means no indicator will be shown while downloading.
+ public var indicatorType: IndicatorType {
+ get {
+ return getAssociatedObject(base, &indicatorTypeKey) ?? .none
+ }
+
+ set {
+ switch newValue {
+ case .none: indicator = nil
+ case .activity: indicator = ActivityIndicator()
+ case .image(let data): indicator = ImageIndicator(imageData: data)
+ case .custom(let anIndicator): indicator = anIndicator
+ }
+
+ setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
+ }
+ }
+
+ /// Holds any type that conforms to the protocol `Indicator`.
+ /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
+ /// It will be `nil` if `indicatorType` is `.none`.
+ public private(set) var indicator: Indicator? {
+ get {
+ let box: Box? = getAssociatedObject(base, &indicatorKey)
+ return box?.value
+ }
+
+ set {
+ // Remove previous
+ if let previousIndicator = indicator {
+ previousIndicator.view.removeFromSuperview()
+ }
+
+ // Add new
+ if let newIndicator = newValue {
+ // Set default indicator layout
+ let view = newIndicator.view
+
+ base.addSubview(view)
+ view.translatesAutoresizingMaskIntoConstraints = false
+ view.centerXAnchor.constraint(
+ equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
+ view.centerYAnchor.constraint(
+ equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
+
+ newIndicator.view.isHidden = true
+ }
+
+ // Save in associated object
+ // Wrap newValue with Box to workaround an issue that Swift does not recognize
+ // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
+ setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
+ }
+ }
+
+ private var imageTask: DownloadTask? {
+ get { return getAssociatedObject(base, &imageTaskKey) }
+ set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+ }
+
+ /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
+ /// it is downloading an image.
+ public private(set) var placeholder: Placeholder? {
+ get { return getAssociatedObject(base, &placeholderKey) }
+ set {
+ if let previousPlaceholder = placeholder {
+ previousPlaceholder.remove(from: base)
+ }
+
+ if let newPlaceholder = newValue {
+ newPlaceholder.add(to: base)
+ } else {
+ base.image = nil
+ }
+ setRetainedAssociatedObject(base, &placeholderKey, newValue)
+ }
+ }
+}
+
+
+@objc extension ImageView {
+ func shouldPreloadAllAnimation() -> Bool { return true }
+}
+
+extension KingfisherWrapper where Base: ImageView {
+ /// Gets the image URL bound to this image view.
+ @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
+ public private(set) var webURL: URL? {
+ get { return nil }
+ set { }
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
new file mode 100644
index 0000000..64ddc92
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift
@@ -0,0 +1,390 @@
+//
+// UIButton+Kingfisher.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/13.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 UIKit
+
+extension KingfisherWrapper where Base: UIButton {
+
+ // MARK: Setting Image
+ /// Sets an image to the button for a specified state with a source.
+ ///
+ /// - Parameters:
+ /// - source: The `Source` object contains information about the image.
+ /// - state: The button state to which the image should be set.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache
+ /// or network. Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setImage(
+ with source: Source?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ guard let source = source else {
+ base.setImage(placeholder, for: state)
+ setTaskIdentifier(nil, for: state)
+ completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+ return nil
+ }
+
+ var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+ if !options.keepCurrentImageWhileLoading {
+ base.setImage(placeholder, for: state)
+ }
+
+ var mutatingSelf = self
+ let issuedIdentifier = Source.Identifier.next()
+ setTaskIdentifier(issuedIdentifier, for: state)
+
+ if let block = progressBlock {
+ options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+ }
+
+ if let provider = ImageProgressiveProvider(options, refresh: { image in
+ self.base.setImage(image, for: state)
+ }) {
+ options.onDataReceived = (options.onDataReceived ?? []) + [provider]
+ }
+
+ options.onDataReceived?.forEach {
+ $0.onShouldApply = { issuedIdentifier == self.taskIdentifier(for: state) }
+ }
+
+ let task = KingfisherManager.shared.retrieveImage(
+ with: source,
+ options: options,
+ completionHandler: { result in
+ CallbackQueue.mainCurrentOrAsync.execute {
+ guard issuedIdentifier == self.taskIdentifier(for: state) else {
+ let reason: KingfisherError.ImageSettingErrorReason
+ do {
+ let value = try result.get()
+ reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+ } catch {
+ reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+ }
+ let error = KingfisherError.imageSettingError(reason: reason)
+ completionHandler?(.failure(error))
+ return
+ }
+
+ mutatingSelf.imageTask = nil
+ mutatingSelf.setTaskIdentifier(nil, for: state)
+
+ switch result {
+ case .success(let value):
+ self.base.setImage(value.image, for: state)
+ completionHandler?(result)
+
+ case .failure:
+ if let image = options.onFailureImage {
+ self.base.setImage(image, for: state)
+ }
+ completionHandler?(result)
+ }
+ }
+ }
+ )
+
+ mutatingSelf.imageTask = task
+ return task
+ }
+
+ /// Sets an image to the button for a specified state with a requested resource.
+ ///
+ /// - Parameters:
+ /// - resource: The `Resource` object contains information about the resource.
+ /// - state: The button state to which the image should be set.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+ /// or network. Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setImage(
+ with resource: Resource?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ return setImage(
+ with: resource.map { Source.network($0) },
+ for: state,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+ // MARK: Cancelling Downloading Task
+
+ /// Cancels the image download task of the button if it is running.
+ /// Nothing will happen if the downloading has already finished.
+ public func cancelImageDownloadTask() {
+ imageTask?.cancel()
+ }
+
+ // MARK: Setting Background Image
+
+ /// Sets a background image to the button for a specified state with a source.
+ ///
+ /// - Parameters:
+ /// - source: The `Source` object contains information about the image.
+ /// - state: The button state to which the image should be set.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// Internally, this method will use `KingfisherManager` to get the requested source
+ /// Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setBackgroundImage(
+ with source: Source?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ guard let source = source else {
+ base.setBackgroundImage(placeholder, for: state)
+ setBackgroundTaskIdentifier(nil, for: state)
+ completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
+ return nil
+ }
+
+ var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
+ if !options.keepCurrentImageWhileLoading {
+ base.setBackgroundImage(placeholder, for: state)
+ }
+
+ var mutatingSelf = self
+ let issuedIdentifier = Source.Identifier.next()
+ setBackgroundTaskIdentifier(issuedIdentifier, for: state)
+
+ if let block = progressBlock {
+ options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+ }
+
+ if let provider = ImageProgressiveProvider(options, refresh: { image in
+ self.base.setBackgroundImage(image, for: state)
+ }) {
+ options.onDataReceived = (options.onDataReceived ?? []) + [provider]
+ }
+
+ options.onDataReceived?.forEach {
+ $0.onShouldApply = { issuedIdentifier == self.backgroundTaskIdentifier(for: state) }
+ }
+
+ let task = KingfisherManager.shared.retrieveImage(
+ with: source,
+ options: options,
+ completionHandler: { result in
+ CallbackQueue.mainCurrentOrAsync.execute {
+ guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else {
+ let reason: KingfisherError.ImageSettingErrorReason
+ do {
+ let value = try result.get()
+ reason = .notCurrentSourceTask(result: value, error: nil, source: source)
+ } catch {
+ reason = .notCurrentSourceTask(result: nil, error: error, source: source)
+ }
+ let error = KingfisherError.imageSettingError(reason: reason)
+ completionHandler?(.failure(error))
+ return
+ }
+
+ mutatingSelf.backgroundImageTask = nil
+ mutatingSelf.setBackgroundTaskIdentifier(nil, for: state)
+
+ switch result {
+ case .success(let value):
+ self.base.setBackgroundImage(value.image, for: state)
+ completionHandler?(result)
+
+ case .failure:
+ if let image = options.onFailureImage {
+ self.base.setBackgroundImage(image, for: state)
+ }
+ completionHandler?(result)
+ }
+ }
+ }
+ )
+
+ mutatingSelf.backgroundImageTask = task
+ return task
+ }
+
+ /// Sets a background image to the button for a specified state with a requested resource.
+ ///
+ /// - Parameters:
+ /// - resource: The `Resource` object contains information about the resource.
+ /// - state: The button state to which the image should be set.
+ /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
+ /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called.
+ /// - completionHandler: Called when the image retrieved and set finished.
+ /// - Returns: A task represents the image downloading.
+ ///
+ /// - Note:
+ /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
+ /// or network. Since this method will perform UI changes, you must call it from the main thread.
+ /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
+ ///
+ @discardableResult
+ public func setBackgroundImage(
+ with resource: Resource?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)? = nil) -> DownloadTask?
+ {
+ return setBackgroundImage(
+ with: resource.map { .network($0) },
+ for: state,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock,
+ completionHandler: completionHandler)
+ }
+
+ // MARK: Cancelling Background Downloading Task
+
+ /// Cancels the background image download task of the button if it is running.
+ /// Nothing will happen if the downloading has already finished.
+ public func cancelBackgroundImageDownloadTask() {
+ backgroundImageTask?.cancel()
+ }
+}
+
+// MARK: - Associated Object
+private var taskIdentifierKey: Void?
+private var imageTaskKey: Void?
+
+// MARK: Properties
+extension KingfisherWrapper where Base: UIButton {
+
+ private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]>
+
+ public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
+ return taskIdentifierInfo.value[state.rawValue]
+ }
+
+ private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
+ taskIdentifierInfo.value[state.rawValue] = identifier
+ }
+
+ private var taskIdentifierInfo: TaskIdentifier {
+ return getAssociatedObject(base, &taskIdentifierKey) ?? {
+ setRetainedAssociatedObject(base, &taskIdentifierKey, $0)
+ return $0
+ } (TaskIdentifier([:]))
+ }
+
+ private var imageTask: DownloadTask? {
+ get { return getAssociatedObject(base, &imageTaskKey) }
+ set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
+ }
+}
+
+
+private var backgroundTaskIdentifierKey: Void?
+private var backgroundImageTaskKey: Void?
+
+// MARK: Background Properties
+extension KingfisherWrapper where Base: UIButton {
+
+ public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
+ return backgroundTaskIdentifierInfo.value[state.rawValue]
+ }
+
+ private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
+ backgroundTaskIdentifierInfo.value[state.rawValue] = identifier
+ }
+
+ private var backgroundTaskIdentifierInfo: TaskIdentifier {
+ return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? {
+ setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0)
+ return $0
+ } (TaskIdentifier([:]))
+ }
+
+ private var backgroundImageTask: DownloadTask? {
+ get { return getAssociatedObject(base, &backgroundImageTaskKey) }
+ mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) }
+ }
+}
+
+extension KingfisherWrapper where Base: UIButton {
+
+ /// Gets the image URL of this button for a specified state.
+ ///
+ /// - Parameter state: The state that uses the specified image.
+ /// - Returns: Current URL for image.
+ @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
+ public func webURL(for state: UIControl.State) -> URL? {
+ return nil
+ }
+
+ /// Gets the background image URL of this button for a specified state.
+ ///
+ /// - Parameter state: The state that uses the specified background image.
+ /// - Returns: Current URL for image.
+ @available(*, deprecated, message: "Use `backgroundTaskIdentifier` instead to identify a setting task.")
+ public func backgroundWebURL(for state: UIControl.State) -> URL? {
+ return nil
+ }
+}
diff --git a/Pods/Kingfisher/Sources/General/Deprecated.swift b/Pods/Kingfisher/Sources/General/Deprecated.swift
new file mode 100644
index 0000000..fa47a33
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/Deprecated.swift
@@ -0,0 +1,654 @@
+//
+// Deprecated.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/09/28.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 canImport(AppKit)
+import AppKit
+#elseif canImport(UIKit)
+import UIKit
+#endif
+
+// MARK: - Deprecated
+extension KingfisherWrapper where Base: Image {
+ @available(*, deprecated, message:
+ "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `image(with:options:)` instead.")
+ public static func image(
+ data: Data,
+ scale: CGFloat,
+ preloadAllAnimationData: Bool,
+ onlyFirstFrame: Bool) -> Image?
+ {
+ let options = ImageCreatingOptions(
+ scale: scale,
+ duration: 0.0,
+ preloadAll: preloadAllAnimationData,
+ onlyFirstFrame: onlyFirstFrame)
+ return KingfisherWrapper.image(data: data, options: options)
+ }
+
+ @available(*, deprecated, message:
+ "Will be removed soon. Pass parameters with `ImageCreatingOptions`, use `animatedImage(with:options:)` instead.")
+ public static func animated(
+ with data: Data,
+ scale: CGFloat = 1.0,
+ duration: TimeInterval = 0.0,
+ preloadAll: Bool,
+ onlyFirstFrame: Bool = false) -> Image?
+ {
+ let options = ImageCreatingOptions(
+ scale: scale, duration: duration, preloadAll: preloadAll, onlyFirstFrame: onlyFirstFrame)
+ return animatedImage(data: data, options: options)
+ }
+}
+
+@available(*, deprecated, message: "Will be removed soon. Use `Result` based callback instead")
+public typealias CompletionHandler =
+ ((_ image: Image?, _ error: NSError?, _ cacheType: CacheType, _ imageURL: URL?) -> Void)
+
+@available(*, deprecated, message: "Will be removed soon. Use `Result` based callback instead")
+public typealias ImageDownloaderCompletionHandler =
+ ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> Void)
+
+// MARK: - Deprecated
+@available(*, deprecated, message: "Will be removed soon. Use `DownloadTask` to cancel a task.")
+extension RetrieveImageTask {
+ @available(*, deprecated, message: "RetrieveImageTask.empty will be removed soon. Use `nil` to represent a no task.")
+ public static let empty = RetrieveImageTask()
+}
+
+// MARK: - Deprecated
+extension KingfisherManager {
+ /// Get an image with resource.
+ /// If `.empty` is used as `options`, Kingfisher will seek the image in memory and disk first.
+ /// If not found, it will download the image at `resource.downloadURL` and cache it with `resource.cacheKey`.
+ /// These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
+ ///
+ /// - Parameters:
+ /// - resource: Resource object contains information such as `cacheKey` and `downloadURL`.
+ /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
+ /// - progressBlock: Called every time downloaded data changed. This could be used as a progress UI.
+ /// - completionHandler: Called when the whole retrieving process finished.
+ /// - Returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ public func retrieveImage(with resource: Resource,
+ options: KingfisherOptionsInfo?,
+ progressBlock: DownloadProgressBlock?,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return retrieveImage(with: resource, options: options, progressBlock: progressBlock) {
+ result in
+ switch result {
+ case .success(let value): completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error): completionHandler?(nil, error as NSError, .none, resource.downloadURL)
+ }
+ }
+ }
+}
+
+// MARK: - Deprecated
+extension ImageDownloader {
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ open func downloadImage(with url: URL,
+ retrieveImageTask: RetrieveImageTask? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: ImageDownloaderProgressBlock? = nil,
+ completionHandler: ImageDownloaderCompletionHandler?) -> DownloadTask?
+ {
+ return downloadImage(with: url, options: options, progressBlock: progressBlock) {
+ result in
+ switch result {
+ case .success(let value): completionHandler?(value.image, nil, value.url, value.originalData)
+ case .failure(let error): completionHandler?(nil, error as NSError, nil, nil)
+ }
+ }
+ }
+}
+
+@available(*, deprecated, message: "RetrieveImageDownloadTask is removed. Use `DownloadTask` to cancel a task.")
+public struct RetrieveImageDownloadTask {
+}
+
+@available(*, deprecated, message: "RetrieveImageTask is removed. Use `DownloadTask` to cancel a task.")
+public final class RetrieveImageTask {
+}
+
+@available(*, deprecated, message: "Use `DownloadProgressBlock` instead.", renamed: "DownloadProgressBlock")
+public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
+
+#if !os(watchOS)
+// MARK: - Deprecated
+extension KingfisherWrapper where Base: ImageView {
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ public func setImage(with resource: Resource?,
+ placeholder: Placeholder? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock) {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+}
+#endif
+
+#if canImport(UIKit) && !os(watchOS)
+// MARK: - Deprecated
+extension KingfisherWrapper where Base: UIButton {
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ public func setImage(
+ with resource: Resource?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setImage(
+ with: resource,
+ for: state,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock)
+ {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ public func setBackgroundImage(
+ with resource: Resource?,
+ for state: UIControl.State,
+ placeholder: UIImage? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setBackgroundImage(
+ with: resource,
+ for: state,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock)
+ {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+}
+#endif
+
+#if os(watchOS)
+import WatchKit
+// MARK: - Deprecated
+extension KingfisherWrapper where Base: WKInterfaceImage {
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ @discardableResult
+ public func setImage(_ resource: Resource?,
+ placeholder: Image? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setImage(
+ with: resource,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock)
+ {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+}
+#endif
+
+#if os(macOS)
+// MARK: - Deprecated
+extension KingfisherWrapper where Base: NSButton {
+ @discardableResult
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ public func setImage(with resource: Resource?,
+ placeholder: Image? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setImage(
+ with: resource,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock)
+ {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+
+ @discardableResult
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ public func setAlternateImage(with resource: Resource?,
+ placeholder: Image? = nil,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: CompletionHandler?) -> DownloadTask?
+ {
+ return setAlternateImage(
+ with: resource,
+ placeholder: placeholder,
+ options: options,
+ progressBlock: progressBlock)
+ {
+ result in
+ switch result {
+ case .success(let value):
+ completionHandler?(value.image, nil, value.cacheType, value.source.url)
+ case .failure(let error):
+ completionHandler?(nil, error as NSError, .none, nil)
+ }
+ }
+ }
+}
+#endif
+
+// MARK: - Deprecated
+extension ImageCache {
+ /// The largest cache cost of memory cache. The total cost is pixel count of
+ /// all cached images in memory.
+ /// Default is unlimited. Memory cache will be purged automatically when a
+ /// memory warning notification is received.
+ @available(*, deprecated, message: "Use `memoryStorage.config.totalCostLimit` instead.",
+ renamed: "memoryStorage.config.totalCostLimit")
+ open var maxMemoryCost: Int {
+ get { return memoryStorage.config.totalCostLimit }
+ set { memoryStorage.config.totalCostLimit = newValue }
+ }
+
+ /// The default DiskCachePathClosure
+ @available(*, deprecated, message: "Not needed anymore.")
+ public final class func defaultDiskCachePathClosure(path: String?, cacheName: String) -> String {
+ let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
+ return (dstPath as NSString).appendingPathComponent(cacheName)
+ }
+
+ /// The default file extension appended to cached files.
+ @available(*, deprecated, message: "Use `diskStorage.config.pathExtension` instead.",
+ renamed: "diskStorage.config.pathExtension")
+ open var pathExtension: String? {
+ get { return diskStorage.config.pathExtension }
+ set { diskStorage.config.pathExtension = newValue }
+ }
+
+ ///The disk cache location.
+ @available(*, deprecated, message: "Use `diskStorage.directoryURL.absoluteString` instead.",
+ renamed: "diskStorage.directoryURL.absoluteString")
+ public var diskCachePath: String {
+ return diskStorage.directoryURL.absoluteString
+ }
+
+ /// The largest disk size can be taken for the cache. It is the total
+ /// allocated size of cached files in bytes.
+ /// Default is no limit.
+ @available(*, deprecated, message: "Use `diskStorage.config.sizeLimit` instead.",
+ renamed: "diskStorage.config.sizeLimit")
+ open var maxDiskCacheSize: UInt {
+ get { return UInt(diskStorage.config.sizeLimit) }
+ set { diskStorage.config.sizeLimit = newValue }
+ }
+
+ @available(*, deprecated, message: "Use `diskStorage.cacheFileURL(forKey:).path` instead.",
+ renamed: "diskStorage.cacheFileURL(forKey:)")
+ open func cachePath(forComputedKey key: String) -> String {
+ return diskStorage.cacheFileURL(forKey: key).path
+ }
+
+ /**
+ Get an image for a key from disk.
+
+ - parameter key: Key for the image.
+ - parameter options: Options of retrieving image. If you need to retrieve an image which was
+ stored with a specified `ImageProcessor`, pass the processor in the option too.
+
+ - returns: The image object if it is cached, or `nil` if there is no such key in the cache.
+ */
+ @available(*, deprecated,
+ message: "Use `Result` based `retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)` instead.",
+ renamed: "retrieveImageInDiskCache(forKey:options:callbackQueue:completionHandler:)")
+ open func retrieveImageInDiskCache(forKey key: String, options: KingfisherOptionsInfo? = nil) -> Image? {
+ let options = options ?? .empty
+ let computedKey = key.computedKey(with: options.processor.identifier)
+ do {
+ if let data = try diskStorage.value(forKey: computedKey) {
+ return options.cacheSerializer.image(with: data, options: options)
+ }
+ } catch {}
+ return nil
+ }
+
+ @available(*, deprecated,
+ message: "Use `Result` based `retrieveImage(forKey:options:callbackQueue:completionHandler:)` instead.",
+ renamed: "retrieveImage(forKey:options:callbackQueue:completionHandler:)")
+ open func retrieveImage(forKey key: String,
+ options: KingfisherOptionsInfo?,
+ completionHandler: ((Image?, CacheType) -> Void)?)
+ {
+ retrieveImage(
+ forKey: key,
+ options: options,
+ callbackQueue: .dispatch((options ?? .empty).callbackDispatchQueue))
+ {
+ result in
+ do {
+ let value = try result.get()
+ completionHandler?(value.image, value.cacheType)
+ } catch {
+ completionHandler?(nil, .none)
+ }
+ }
+ }
+
+ /// The longest time duration in second of the cache being stored in disk.
+ /// Default is 1 week (60 * 60 * 24 * 7 seconds).
+ /// Setting this to a negative value will make the disk cache never expiring.
+ @available(*, deprecated, message: "Deprecated. Use `diskStorage.config.expiration` instead")
+ open var maxCachePeriodInSecond: TimeInterval {
+ get { return diskStorage.config.expiration.timeInterval }
+ set { diskStorage.config.expiration = newValue < 0 ? .never : .seconds(newValue) }
+ }
+
+ @available(*, deprecated, message: "Use `Result` based callback instead.")
+ open func store(_ image: Image,
+ original: Data? = nil,
+ forKey key: String,
+ processorIdentifier identifier: String = "",
+ cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default,
+ toDisk: Bool = true,
+ completionHandler: (() -> Void)?)
+ {
+ store(
+ image,
+ original: original,
+ forKey: key,
+ processorIdentifier: identifier,
+ cacheSerializer: serializer,
+ toDisk: toDisk)
+ {
+ _ in
+ completionHandler?()
+ }
+ }
+
+ @available(*, deprecated, message: "Use the `Result`-based `calculateDiskStorageSize` instead.")
+ open func calculateDiskCacheSize(completion handler: @escaping ((_ size: UInt) -> Void)) {
+ calculateDiskStorageSize { result in
+ let size: UInt? = try? result.get()
+ handler(size ?? 0)
+ }
+ }
+}
+
+// MARK: - Deprecated
+extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
+ /// The queue of callbacks should happen from Kingfisher.
+ @available(*, deprecated, message: "Use `callbackQueue` instead.", renamed: "callbackQueue")
+ public var callbackDispatchQueue: DispatchQueue {
+ return KingfisherParsedOptionsInfo(Array(self)).callbackQueue.queue
+ }
+}
+
+/// Error domain of Kingfisher
+@available(*, deprecated, message: "Use `KingfisherError.domain` instead.", renamed: "KingfisherError.domain")
+public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
+
+/// Key will be used in the `userInfo` of `.invalidStatusCode`
+@available(*, unavailable,
+message: "Use `.invalidHTTPStatusCode` or `isInvalidResponseStatusCode` of `KingfisherError` instead for the status code.")
+public let KingfisherErrorStatusCodeKey = "statusCode"
+
+// MARK: - Deprecated
+extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
+ /// The target `ImageCache` which is used.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `targetCache` instead.")
+ public var targetCache: ImageCache? {
+ return KingfisherParsedOptionsInfo(Array(self)).targetCache
+ }
+
+ /// The original `ImageCache` which is used.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `originalCache` instead.")
+ public var originalCache: ImageCache? {
+ return KingfisherParsedOptionsInfo(Array(self)).originalCache
+ }
+
+ /// The `ImageDownloader` which is specified.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloader` instead.")
+ public var downloader: ImageDownloader? {
+ return KingfisherParsedOptionsInfo(Array(self)).downloader
+ }
+
+ /// Member for animation transition when using UIImageView.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `transition` instead.")
+ public var transition: ImageTransition {
+ return KingfisherParsedOptionsInfo(Array(self)).transition
+ }
+
+ /// A `Float` value set as the priority of image download task. The value for it should be
+ /// between 0.0~1.0.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `downloadPriority` instead.")
+ public var downloadPriority: Float {
+ return KingfisherParsedOptionsInfo(Array(self)).downloadPriority
+ }
+
+ /// Whether an image will be always downloaded again or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceRefresh` instead.")
+ public var forceRefresh: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).forceRefresh
+ }
+
+ /// Whether an image should be got only from memory cache or download.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `fromMemoryCacheOrRefresh` instead.")
+ public var fromMemoryCacheOrRefresh: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).fromMemoryCacheOrRefresh
+ }
+
+ /// Whether the transition should always happen or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `forceTransition` instead.")
+ public var forceTransition: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).forceTransition
+ }
+
+ /// Whether cache the image only in memory or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheMemoryOnly` instead.")
+ public var cacheMemoryOnly: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).cacheMemoryOnly
+ }
+
+ /// Whether the caching operation will be waited or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `waitForCache` instead.")
+ public var waitForCache: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).waitForCache
+ }
+
+ /// Whether only load the images from cache or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyFromCache` instead.")
+ public var onlyFromCache: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).onlyFromCache
+ }
+
+ /// Whether the image should be decoded in background or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `backgroundDecode` instead.")
+ public var backgroundDecode: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).backgroundDecode
+ }
+
+ /// Whether the image data should be all loaded at once if it is an animated image.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `preloadAllAnimationData` instead.")
+ public var preloadAllAnimationData: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).preloadAllAnimationData
+ }
+
+ /// The `CallbackQueue` on which completion handler should be invoked.
+ /// If not set in the options, `.mainCurrentOrAsync` will be used.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `callbackQueue` instead.")
+ public var callbackQueue: CallbackQueue {
+ return KingfisherParsedOptionsInfo(Array(self)).callbackQueue
+ }
+
+ /// The scale factor which should be used for the image.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `scaleFactor` instead.")
+ public var scaleFactor: CGFloat {
+ return KingfisherParsedOptionsInfo(Array(self)).scaleFactor
+ }
+
+ /// The `ImageDownloadRequestModifier` will be used before sending a download request.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `requestModifier` instead.")
+ public var modifier: ImageDownloadRequestModifier? {
+ return KingfisherParsedOptionsInfo(Array(self)).requestModifier
+ }
+
+ /// `ImageProcessor` for processing when the downloading finishes.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `processor` instead.")
+ public var processor: ImageProcessor {
+ return KingfisherParsedOptionsInfo(Array(self)).processor
+ }
+
+ /// `ImageModifier` for modifying right before the image is displayed.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `imageModifier` instead.")
+ public var imageModifier: ImageModifier? {
+ return KingfisherParsedOptionsInfo(Array(self)).imageModifier
+ }
+
+ /// `CacheSerializer` to convert image to data for storing in cache.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheSerializer` instead.")
+ public var cacheSerializer: CacheSerializer {
+ return KingfisherParsedOptionsInfo(Array(self)).cacheSerializer
+ }
+
+ /// Keep the existing image while setting another image to an image view.
+ /// Or the placeholder will be used while downloading.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `keepCurrentImageWhileLoading` instead.")
+ public var keepCurrentImageWhileLoading: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).keepCurrentImageWhileLoading
+ }
+
+ /// Whether the options contains `.onlyLoadFirstFrame`.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onlyLoadFirstFrame` instead.")
+ public var onlyLoadFirstFrame: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).onlyLoadFirstFrame
+ }
+
+ /// Whether the options contains `.cacheOriginalImage`.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `cacheOriginalImage` instead.")
+ public var cacheOriginalImage: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).cacheOriginalImage
+ }
+
+ /// The image which should be used when download image request fails.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `onFailureImage` instead.")
+ public var onFailureImage: Optional {
+ return KingfisherParsedOptionsInfo(Array(self)).onFailureImage
+ }
+
+ /// Whether the `ImagePrefetcher` should load images to memory in an aggressive way or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `alsoPrefetchToMemory` instead.")
+ public var alsoPrefetchToMemory: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).alsoPrefetchToMemory
+ }
+
+ /// Whether the disk storage file loading should happen in a synchronous behavior or not.
+ @available(*, deprecated,
+ message: "Create a `KingfisherParsedOptionsInfo` from `KingfisherOptionsInfo` and use `loadDiskFileSynchronously` instead.")
+ public var loadDiskFileSynchronously: Bool {
+ return KingfisherParsedOptionsInfo(Array(self)).loadDiskFileSynchronously
+ }
+}
+
+/// The default modifier.
+/// It does nothing and returns the image as is.
+@available(*, deprecated, message: "Use `nil` in KingfisherOptionsInfo to indicate no modifier.")
+public struct DefaultImageModifier: ImageModifier {
+
+ /// A default `DefaultImageModifier` which can be used everywhere.
+ public static let `default` = DefaultImageModifier()
+ private init() {}
+
+ /// Modifies an input `Image`. See `ImageModifier` protocol for more.
+ public func modify(_ image: Image) -> Image { return image }
+}
diff --git a/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
new file mode 100644
index 0000000..c387409
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
@@ -0,0 +1,145 @@
+//
+// ImageDataProvider.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/11/13.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 data provider to provide image data to Kingfisher when setting with
+/// `Source.provider` source. Compared to `Source.network` member, it gives a chance
+/// to load some image data in your own way, as long as you can provide the data
+/// representation for the image.
+public protocol ImageDataProvider {
+
+ /// The key used in cache.
+ var cacheKey: String { get }
+
+ /// Provides the data which represents image. Kingfisher uses the data you pass in the
+ /// handler to process images and caches it for later use.
+ ///
+ /// - Parameter handler: The handler you should call when you prepared your data.
+ /// If the data is loaded successfully, call the handler with
+ /// a `.success` with the data associated. Otherwise, call it
+ /// with a `.failure` and pass the error.
+ ///
+ /// - Note:
+ /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of
+ /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError`
+ /// from the framework.
+ func data(handler: @escaping (Result) -> Void)
+}
+
+/// Represents an image data provider for loading from a local file URL on disk.
+/// Uses this type for adding a disk image to Kingfisher. Compared to loading it
+/// directly, you can get benefit of using Kingfisher's extension methods, as well
+/// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher.
+public struct LocalFileImageDataProvider: ImageDataProvider {
+
+ // MARK: Public Properties
+
+ /// The file URL from which the image be loaded.
+ public let fileURL: URL
+
+ // MARK: Initializers
+
+ /// Creates an image data provider by supplying the target local file URL.
+ ///
+ /// - Parameters:
+ /// - fileURL: The file URL from which the image be loaded.
+ /// - cacheKey: The key is used for caching the image data. By default,
+ /// the `absoluteString` of `fileURL` is used.
+ public init(fileURL: URL, cacheKey: String? = nil) {
+ self.fileURL = fileURL
+ self.cacheKey = cacheKey ?? fileURL.absoluteString
+ }
+
+ // MARK: Protocol Conforming
+
+ /// The key used in cache.
+ public var cacheKey: String
+
+ public func data(handler: (Result) -> Void) {
+ handler(Result(catching: { try Data(contentsOf: fileURL) }))
+ }
+}
+
+/// Represents an image data provider for loading image from a given Base64 encoded string.
+public struct Base64ImageDataProvider: ImageDataProvider {
+
+ // MARK: Public Properties
+ /// The encoded Base64 string for the image.
+ public let base64String: String
+
+ // MARK: Initializers
+
+ /// Creates an image data provider by supplying the Base64 encoded string.
+ ///
+ /// - Parameters:
+ /// - base64String: The Base64 encoded string for an image.
+ /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
+ public init(base64String: String, cacheKey: String) {
+ self.base64String = base64String
+ self.cacheKey = cacheKey
+ }
+
+ // MARK: Protocol Conforming
+
+ /// The key used in cache.
+ public var cacheKey: String
+
+ public func data(handler: (Result) -> Void) {
+ let data = Data(base64Encoded: base64String)!
+ handler(.success(data))
+ }
+}
+
+/// Represents an image data provider for a raw data object.
+public struct RawImageDataProvider: ImageDataProvider {
+
+ // MARK: Public Properties
+
+ /// The raw data object to provide to Kingfisher image loader.
+ public let data: Data
+
+ // MARK: Initializers
+
+ /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache.
+ ///
+ /// - Parameters:
+ /// - data: The raw data reprensents an image.
+ /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
+ public init(data: Data, cacheKey: String) {
+ self.data = data
+ self.cacheKey = cacheKey
+ }
+
+ // MARK: Protocol Conforming
+
+ /// The key used in cache.
+ public var cacheKey: String
+
+ public func data(handler: @escaping (Result) -> Void) {
+ handler(.success(data))
+ }
+}
diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift
new file mode 100644
index 0000000..f12d8a9
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift
@@ -0,0 +1,74 @@
+//
+// Resource.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/6.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 an image resource at a certain url and a given cache key.
+/// Kingfisher will use a `Resource` to download a resource from network and cache it with the cache key when
+/// using `Source.network` as its image setting source.
+public protocol Resource {
+
+ /// The key used in cache.
+ var cacheKey: String { get }
+
+ /// The target image URL.
+ var downloadURL: URL { get }
+}
+
+/// ImageResource is a simple combination of `downloadURL` and `cacheKey`.
+/// When passed to image view set methods, Kingfisher will try to download the target
+/// image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache.
+public struct ImageResource: Resource {
+
+ // MARK: - Initializers
+
+ /// Creates an image resource.
+ ///
+ /// - Parameters:
+ /// - downloadURL: The target image URL from where the image can be downloaded.
+ /// - cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key.
+ /// Default is `nil`.
+ public init(downloadURL: URL, cacheKey: String? = nil) {
+ self.downloadURL = downloadURL
+ self.cacheKey = cacheKey ?? downloadURL.absoluteString
+ }
+
+ // MARK: Protocol Conforming
+
+ /// The key used in cache.
+ public let cacheKey: String
+
+ /// The target image URL.
+ public let downloadURL: URL
+}
+
+/// URL conforms to `Resource` in Kingfisher.
+/// The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`.
+/// If you need customize the url and/or cache key, use `ImageResource` instead.
+extension URL: Resource {
+ public var cacheKey: String { return absoluteString }
+ public var downloadURL: URL { return self }
+}
diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Source.swift b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift
new file mode 100644
index 0000000..dd922a2
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift
@@ -0,0 +1,98 @@
+//
+// Source.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/11/17.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 an image setting source for Kingfisher methods.
+///
+/// A `Source` value indicates the way how the target image can be retrieved and cached.
+///
+/// - network: The target image should be got from network remotely. The associated `Resource`
+/// value defines detail information like image URL and cache key.
+/// - provider: The target image should be provided in a data format. Normally, it can be an image
+/// from local storage or in any other encoding format (like Base64).
+public enum Source {
+
+ /// Represents the source task identifier when setting an image to a view with extension methods.
+ public enum Identifier {
+
+ /// The underlying value type of source identifier.
+ public typealias Value = UInt
+ static var current: Value = 0
+ static func next() -> Value {
+ current += 1
+ return current
+ }
+ }
+
+ // MARK: Member Cases
+
+ /// The target image should be got from network remotely. The associated `Resource`
+ /// value defines detail information like image URL and cache key.
+ case network(Resource)
+
+ /// The target image should be provided in a data format. Normally, it can be an image
+ /// from local storage or in any other encoding format (like Base64).
+ case provider(ImageDataProvider)
+
+ // MARK: Getting Properties
+
+ /// The cache key defined for this source value.
+ public var cacheKey: String {
+ switch self {
+ case .network(let resource): return resource.cacheKey
+ case .provider(let provider): return provider.cacheKey
+ }
+ }
+
+ /// The URL defined for this source value.
+ ///
+ /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance.
+ /// For a `.provider` value, it is always `nil`.
+ public var url: URL? {
+ switch self {
+ case .network(let resource): return resource.downloadURL
+ // `ImageDataProvider` does not provide a URL. All it cares is how to get the data back.
+ case .provider(_): return nil
+ }
+ }
+}
+
+extension Source {
+ var asResource: Resource? {
+ guard case .network(let resource) = self else {
+ return nil
+ }
+ return resource
+ }
+
+ var asProvider: ImageDataProvider? {
+ guard case .provider(let provider) = self else {
+ return nil
+ }
+ return provider
+ }
+}
diff --git a/Pods/Kingfisher/Sources/General/Kingfisher.swift b/Pods/Kingfisher/Sources/General/Kingfisher.swift
new file mode 100644
index 0000000..4098401
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/Kingfisher.swift
@@ -0,0 +1,89 @@
+//
+// Kingfisher.swift
+// Kingfisher
+//
+// Created by Wei Wang on 16/9/14.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 ImageIO
+
+#if os(macOS)
+import AppKit
+public typealias Image = NSImage
+public typealias View = NSView
+public typealias Color = NSColor
+public typealias ImageView = NSImageView
+public typealias Button = NSButton
+#else
+import UIKit
+public typealias Image = UIImage
+public typealias Color = UIColor
+#if !os(watchOS)
+public typealias ImageView = UIImageView
+public typealias View = UIView
+public typealias Button = UIButton
+#else
+import WatchKit
+#endif
+#endif
+
+/// Wrapper for Kingfisher compatible types. This type provides an extension point for
+/// connivence methods in Kingfisher.
+public struct KingfisherWrapper {
+ public let base: Base
+ public init(_ base: Base) {
+ self.base = base
+ }
+}
+
+/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a
+/// value in the namespace of Kingfisher.
+public protocol KingfisherCompatible: AnyObject { }
+
+/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a
+/// value in the namespace of Kingfisher.
+public protocol KingfisherCompatibleValue {}
+
+extension KingfisherCompatible {
+ /// Gets a namespace holder for Kingfisher compatible types.
+ public var kf: KingfisherWrapper {
+ get { return KingfisherWrapper(self) }
+ set { }
+ }
+}
+
+extension KingfisherCompatibleValue {
+ /// Gets a namespace holder for Kingfisher compatible types.
+ public var kf: KingfisherWrapper {
+ get { return KingfisherWrapper(self) }
+ set { }
+ }
+}
+
+extension Image: KingfisherCompatible { }
+#if !os(watchOS)
+extension ImageView: KingfisherCompatible { }
+extension Button: KingfisherCompatible { }
+#else
+extension WKInterfaceImage: KingfisherCompatible { }
+#endif
diff --git a/Pods/Kingfisher/Sources/General/KingfisherError.swift b/Pods/Kingfisher/Sources/General/KingfisherError.swift
new file mode 100644
index 0000000..2add785
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/KingfisherError.swift
@@ -0,0 +1,400 @@
+//
+// KingfisherError.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/09/26.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+extension Never {}
+
+/// Represents all the errors which can happen in Kingfisher framework.
+/// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError`
+/// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog,
+/// then switch over the reason to know error detail.
+public enum KingfisherError: Error {
+
+ // MARK: Error Reason Types
+
+ /// Represents the error reason during networking request phase.
+ ///
+ /// - emptyRequest: The request is empty. Code 1001.
+ /// - invalidURL: The URL of request is invalid. Code 1002.
+ /// - taskCancelled: The downloading task is cancelled by user. Code 1003.
+ public enum RequestErrorReason {
+
+ /// The request is empty. Code 1001.
+ case emptyRequest
+
+ /// The URL of request is invalid. Code 1002.
+ /// - request: The request is tend to be sent but its URL is invalid.
+ case invalidURL(request: URLRequest)
+
+ /// The downloading task is cancelled by user. Code 1003.
+ /// - task: The session data task which is cancelled.
+ /// - token: The cancel token which is used for cancelling the task.
+ case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken)
+ }
+
+ /// Represents the error reason during networking response phase.
+ ///
+ /// - invalidURLResponse: The response is not a valid URL response. Code 2001.
+ /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002.
+ /// - URLSessionError: An error happens in the system URL session. Code 2003.
+ /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004.
+ /// - noURLResponse: The task is done but no URL response found. Code 2005.
+ public enum ResponseErrorReason {
+
+ /// The response is not a valid URL response. Code 2001.
+ /// - response: The received invalid URL response.
+ /// The response is expected to be an HTTP response, but it is not.
+ case invalidURLResponse(response: URLResponse)
+
+ /// The response contains an invalid HTTP status code. Code 2002.
+ /// - Note:
+ /// By default, status code 200..<400 is recognized as valid. You can override
+ /// this behavior by conforming to the `ImageDownloaderDelegate`.
+ /// - response: The received response.
+ case invalidHTTPStatusCode(response: HTTPURLResponse)
+
+ /// An error happens in the system URL session. Code 2003.
+ /// - error: The underlying URLSession error object.
+ case URLSessionError(error: Error)
+
+ /// Data modifying fails on returning a valid data. Code 2004.
+ /// - task: The failed task.
+ case dataModifyingFailed(task: SessionDataTask)
+
+ /// The task is done but no URL response found. Code 2005.
+ /// - task: The failed task.
+ case noURLResponse(task: SessionDataTask)
+ }
+
+ /// Represents the error reason during Kingfisher caching system.
+ ///
+ /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001.
+ /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002.
+ /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003.
+ /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004.
+ /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005.
+ /// - imageNotExisting: The requested image does not exist in cache. Code 3006.
+ /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007.
+ /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008.
+ public enum CacheErrorReason {
+
+ /// Cannot create a file enumerator for a certain disk URL. Code 3001.
+ /// - url: The target disk URL from which the file enumerator should be created.
+ case fileEnumeratorCreationFailed(url: URL)
+
+ /// Cannot get correct file contents from a file enumerator. Code 3002.
+ /// - url: The target disk URL from which the content of a file enumerator should be got.
+ case invalidFileEnumeratorContent(url: URL)
+
+ /// The file at target URL exists, but its URL resource is unavailable. Code 3003.
+ /// - error: The underlying error thrown by file manager.
+ /// - key: The key used to getting the resource from cache.
+ /// - url: The disk URL where the target cached file exists.
+ case invalidURLResource(error: Error, key: String, url: URL)
+
+ /// The file at target URL exists, but the data cannot be loaded from it. Code 3004.
+ /// - url: The disk URL where the target cached file exists.
+ /// - error: The underlying error which describes why this error happens.
+ case cannotLoadDataFromDisk(url: URL, error: Error)
+
+ /// Cannot create a folder at a given path. Code 3005.
+ /// - path: The disk path where the directory creating operation fails.
+ /// - error: The underlying error which describes why this error happens.
+ case cannotCreateDirectory(path: String, error: Error)
+
+ /// The requested image does not exist in cache. Code 3006.
+ /// - key: Key of the requested image in cache.
+ case imageNotExisting(key: String)
+
+ /// Cannot convert an object to data for storing. Code 3007.
+ /// - object: The object which needs be convert to data.
+ case cannotConvertToData(object: Any, error: Error)
+
+ /// Cannot serialize an image to data for storing. Code 3008.
+ /// - image: The input image needs to be serialized to cache.
+ /// - original: The original image data, if exists.
+ /// - serializer: The `CacheSerializer` used for the image serializing.
+ case cannotSerializeImage(image: Image?, original: Data?, serializer: CacheSerializer)
+ }
+
+
+ /// Represents the error reason during image processing phase.
+ ///
+ /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001.
+ public enum ProcessorErrorReason {
+ /// Image processing fails. There is no valid output image from the processor. Code 4001.
+ /// - processor: The `ImageProcessor` used to process the image or its data in `item`.
+ /// - item: The image or its data content.
+ case processingFailed(processor: ImageProcessor, item: ImageProcessItem)
+ }
+
+ /// Represents the error reason during image setting in a view related class.
+ ///
+ /// - emptySource: The input resource is empty or `nil`. Code 5001.
+ /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002.
+ /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003.
+ public enum ImageSettingErrorReason {
+
+ /// The input resource is empty or `nil`. Code 5001.
+ case emptySource
+
+ /// The resource task is finished, but it is not the one expected now. This usually happens when you set another
+ /// resource on the view without cancelling the current on-going one. The previous setting task will fail with
+ /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task.
+ /// The result of this original task is contained in the associated value.
+ /// Code 5002.
+ /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error
+ /// happens.
+ /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without
+ /// problem.
+ /// - source: The original source value of the taks.
+ case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source)
+
+ /// An error happens during getting data from an `ImageDataProvider`. Code 5003.
+ case dataProviderError(provider: ImageDataProvider, error: Error)
+ }
+
+ // MARK: Member Cases
+
+ /// Represents the error reason during networking request phase.
+ case requestError(reason: RequestErrorReason)
+ /// Represents the error reason during networking response phase.
+ case responseError(reason: ResponseErrorReason)
+ /// Represents the error reason during Kingfisher caching system.
+ case cacheError(reason: CacheErrorReason)
+ /// Represents the error reason during image processing phase.
+ case processorError(reason: ProcessorErrorReason)
+ /// Represents the error reason during image setting in a view related class.
+ case imageSettingError(reason: ImageSettingErrorReason)
+
+ // MARK: Helper Properties & Methods
+
+ /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not.
+ public var isTaskCancelled: Bool {
+ if case .requestError(reason: .taskCancelled) = self {
+ return true
+ }
+ return false
+ }
+
+ /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the
+ /// associated value is a given status code.
+ ///
+ /// - Parameter code: The given status code.
+ /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error
+ /// and its status code equals to `code`, `true` is returned. Otherwise, `false`.
+ public func isInvalidResponseStatusCode(_ code: Int) -> Bool {
+ if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self {
+ return response.statusCode == code
+ }
+ return false
+ }
+
+ public var isInvalidResponseStatusCode: Bool {
+ if case .responseError(reason: .invalidHTTPStatusCode) = self {
+ return true
+ }
+ return false
+ }
+
+ /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not.
+ /// When a new image setting task starts while the old one is still running, the new task identifier will be
+ /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes
+ /// to let you know the setting process finishes with a certain result, but the image view or button is not set.
+ public var isNotCurrentTask: Bool {
+ if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self {
+ return true
+ }
+ return false
+ }
+}
+
+// MARK: - LocalizedError Conforming
+extension KingfisherError: LocalizedError {
+
+ /// A localized message describing what error occurred.
+ public var errorDescription: String? {
+ switch self {
+ case .requestError(let reason): return reason.errorDescription
+ case .responseError(let reason): return reason.errorDescription
+ case .cacheError(let reason): return reason.errorDescription
+ case .processorError(let reason): return reason.errorDescription
+ case .imageSettingError(let reason): return reason.errorDescription
+ }
+ }
+}
+
+
+// MARK: - CustomNSError Conforming
+extension KingfisherError: CustomNSError {
+
+ /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain.
+ public static let domain = "com.onevcat.Kingfisher.Error"
+
+ /// The error code within the given domain.
+ public var errorCode: Int {
+ switch self {
+ case .requestError(let reason): return reason.errorCode
+ case .responseError(let reason): return reason.errorCode
+ case .cacheError(let reason): return reason.errorCode
+ case .processorError(let reason): return reason.errorCode
+ case .imageSettingError(let reason): return reason.errorCode
+ }
+ }
+}
+
+extension KingfisherError.RequestErrorReason {
+ var errorDescription: String? {
+ switch self {
+ case .emptyRequest:
+ return "The request is empty or `nil`."
+ case .invalidURL(let request):
+ return "The request contains an invalid or empty URL. Request: \(request)."
+ case .taskCancelled(let task, let token):
+ return "The session task was cancelled. Task: \(task), cancel token: \(token)."
+ }
+ }
+
+ var errorCode: Int {
+ switch self {
+ case .emptyRequest: return 1001
+ case .invalidURL: return 1002
+ case .taskCancelled: return 1003
+ }
+ }
+}
+
+extension KingfisherError.ResponseErrorReason {
+ var errorDescription: String? {
+ switch self {
+ case .invalidURLResponse(let response):
+ return "The URL response is invalid: \(response)"
+ case .invalidHTTPStatusCode(let response):
+ return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)."
+ case .URLSessionError(let error):
+ return "A URL session error happened. The underlying error: \(error)"
+ case .dataModifyingFailed(let task):
+ return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)."
+ case .noURLResponse(let task):
+ return "No URL response received. Task: \(task),"
+ }
+ }
+
+ var errorCode: Int {
+ switch self {
+ case .invalidURLResponse: return 2001
+ case .invalidHTTPStatusCode: return 2002
+ case .URLSessionError: return 2003
+ case .dataModifyingFailed: return 2004
+ case .noURLResponse: return 2005
+ }
+ }
+}
+
+extension KingfisherError.CacheErrorReason {
+ var errorDescription: String? {
+ switch self {
+ case .fileEnumeratorCreationFailed(let url):
+ return "Cannot create file enumerator for URL: \(url)."
+ case .invalidFileEnumeratorContent(let url):
+ return "Cannot get contents from the file enumerator at URL: \(url)."
+ case .invalidURLResource(let error, let key, let url):
+ return "Cannot get URL resource values or data for the given URL: \(url). " +
+ "Cache key: \(key). Underlying error: \(error)"
+ case .cannotLoadDataFromDisk(let url, let error):
+ return "Cannot load data from disk at URL: \(url). Underlying error: \(error)"
+ case .cannotCreateDirectory(let path, let error):
+ return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)"
+ case .imageNotExisting(let key):
+ return "The image is not in cache, but you requires it should only be " +
+ "from cache by enabling the `.onlyFromCache` option. Key: \(key)."
+ case .cannotConvertToData(let object, let error):
+ return "Cannot convert the input object to a `Data` object when storing it to disk cache. " +
+ "Object: \(object). Underlying error: \(error)"
+ case .cannotSerializeImage(let image, let originalData, let serializer):
+ return "Cannot serialize an image due to the cache serializer returning `nil`. " +
+ "Image: \(String(describing:image)), original data: \(String(describing: originalData)), serializer: \(serializer)."
+ }
+ }
+
+ var errorCode: Int {
+ switch self {
+ case .fileEnumeratorCreationFailed: return 3001
+ case .invalidFileEnumeratorContent: return 3002
+ case .invalidURLResource: return 3003
+ case .cannotLoadDataFromDisk: return 3004
+ case .cannotCreateDirectory: return 3005
+ case .imageNotExisting: return 3006
+ case .cannotConvertToData: return 3007
+ case .cannotSerializeImage: return 3008
+ }
+ }
+}
+
+extension KingfisherError.ProcessorErrorReason {
+ var errorDescription: String? {
+ switch self {
+ case .processingFailed(let processor, let item):
+ return "Processing image failed. Processor: \(processor). Processing item: \(item)."
+ }
+ }
+
+ var errorCode: Int {
+ switch self {
+ case .processingFailed: return 4001
+ }
+ }
+}
+
+extension KingfisherError.ImageSettingErrorReason {
+ var errorDescription: String? {
+ switch self {
+ case .emptySource:
+ return "The input resource is empty."
+ case .notCurrentSourceTask(let result, let error, let resource):
+ if let result = result {
+ return "Retrieving resource succeeded, but this source is " +
+ "not the one currently expected. Result: \(result). Resource: \(resource)."
+ } else if let error = error {
+ return "Retrieving resource failed, and this resource is " +
+ "not the one currently expected. Error: \(error). Resource: \(resource)."
+ } else {
+ return nil
+ }
+ case .dataProviderError(let provider, let error):
+ return "Image data provider fails to provide data. Provider: \(provider), error: \(error)"
+ }
+ }
+
+ var errorCode: Int {
+ switch self {
+ case .emptySource: return 5001
+ case .notCurrentSourceTask: return 5002
+ case .dataProviderError: return 5003
+ }
+ }
+}
diff --git a/Pods/Kingfisher/Sources/General/KingfisherManager.swift b/Pods/Kingfisher/Sources/General/KingfisherManager.swift
new file mode 100644
index 0000000..69473bb
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/KingfisherManager.swift
@@ -0,0 +1,430 @@
+//
+// KingfisherManager.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/6.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+/// The downloading progress block type.
+/// The parameter value is the `receivedSize` of current response.
+/// The second parameter is the total expected data length from response's "Content-Length" header.
+/// If the expected length is not available, this block will not be called.
+public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void)
+
+/// Represents the result of a Kingfisher retrieving image task.
+public struct RetrieveImageResult {
+
+ /// Gets the image object of this result.
+ public let image: Image
+
+ /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved.
+ /// If the image is just downloaded from network, `.none` will be returned.
+ public let cacheType: CacheType
+
+ /// The `Source` from which the retrieve task begins.
+ public let source: Source
+}
+
+/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache,
+/// to provide a set of convenience methods to use Kingfisher for tasks.
+/// You can use this class to retrieve an image via a specified URL from web or cache.
+public class KingfisherManager {
+
+ /// Represents a shared manager used across Kingfisher.
+ /// Use this instance for getting or storing images with Kingfisher.
+ public static let shared = KingfisherManager()
+
+ // Mark: Public Properties
+ /// The `ImageCache` used by this manager. It is `ImageCache.default` by default.
+ /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
+ /// used instead.
+ public var cache: ImageCache
+
+ /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default.
+ /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be
+ /// used instead.
+ public var downloader: ImageDownloader
+
+ /// Default options used by the manager. This option will be used in
+ /// Kingfisher manager related methods, as well as all view extension methods.
+ /// You can also passing other options for each image task by sending an `options` parameter
+ /// to Kingfisher's APIs. The per image options will overwrite the default ones,
+ /// if the option exists in both.
+ public var defaultOptions = KingfisherOptionsInfo.empty
+
+ // Use `defaultOptions` to overwrite the `downloader` and `cache`.
+ private var currentDefaultOptions: KingfisherOptionsInfo {
+ return [.downloader(downloader), .targetCache(cache)] + defaultOptions
+ }
+
+ private let processingQueue: CallbackQueue
+
+ private convenience init() {
+ self.init(downloader: .default, cache: .default)
+ }
+
+ /// Creates an image setting manager with specified downloader and cache.
+ ///
+ /// - Parameters:
+ /// - downloader: The image downloader used to download images.
+ /// - cache: The image cache which stores memory and disk images.
+ public init(downloader: ImageDownloader, cache: ImageCache) {
+ self.downloader = downloader
+ self.cache = cache
+
+ let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)"
+ processingQueue = .dispatch(DispatchQueue(label: processQueueName))
+ }
+
+ // Mark: Getting Images
+
+ /// Gets an image from a given resource.
+ ///
+ /// - Parameters:
+ /// - resource: The `Resource` object defines data information like key or URL.
+ /// - options: Options to use when creating the animated image.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
+ /// main queue.
+ /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
+ /// from the `options.callbackQueue`. If not specified, the main queue will be used.
+ /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
+ /// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
+ ///
+ /// - Note:
+ /// This method will first check whether the requested `resource` is already in cache or not. If cached,
+ /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
+ /// will download the `resource`, store it in cache, then call `completionHandler`.
+ ///
+ @discardableResult
+ public func retrieveImage(
+ with resource: Resource,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)?) -> DownloadTask?
+ {
+ let source = Source.network(resource)
+ return retrieveImage(
+ with: source, options: options, progressBlock: progressBlock, completionHandler: completionHandler
+ )
+ }
+
+ /// Gets an image from a given resource.
+ ///
+ /// - Parameters:
+ /// - source: The `Source` object defines data information from network or a data provider.
+ /// - options: Options to use when creating the animated image.
+ /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
+ /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in
+ /// main queue.
+ /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked
+ /// from the `options.callbackQueue`. If not specified, the main queue will be used.
+ /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource,
+ /// the started `DownloadTask` is returned. Otherwise, `nil` is returned.
+ ///
+ /// - Note:
+ /// This method will first check whether the requested `source` is already in cache or not. If cached,
+ /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it
+ /// will try to load the `source`, store it in cache, then call `completionHandler`.
+ ///
+ public func retrieveImage(
+ with source: Source,
+ options: KingfisherOptionsInfo? = nil,
+ progressBlock: DownloadProgressBlock? = nil,
+ completionHandler: ((Result) -> Void)?) -> DownloadTask?
+ {
+ let options = currentDefaultOptions + (options ?? .empty)
+ var info = KingfisherParsedOptionsInfo(options)
+ if let block = progressBlock {
+ info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
+ }
+ return retrieveImage(
+ with: source,
+ options: info,
+ completionHandler: completionHandler)
+ }
+
+ func retrieveImage(
+ with source: Source,
+ options: KingfisherParsedOptionsInfo,
+ completionHandler: ((Result) -> Void)?) -> DownloadTask?
+ {
+ if options.forceRefresh {
+ return loadAndCacheImage(
+ source: source,
+ options: options,
+ completionHandler: completionHandler)?.value
+
+ } else {
+ let loadedFromCache = retrieveImageFromCache(
+ source: source,
+ options: options,
+ completionHandler: completionHandler)
+
+ if loadedFromCache {
+ return nil
+ }
+
+ if options.onlyFromCache {
+ let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey))
+ completionHandler?(.failure(error))
+ return nil
+ }
+
+ return loadAndCacheImage(
+ source: source,
+ options: options,
+ completionHandler: completionHandler)?.value
+ }
+ }
+
+ func provideImage(
+ provider: ImageDataProvider,
+ options: KingfisherParsedOptionsInfo,
+ completionHandler: ((Result) -> Void)?)
+ {
+ guard let completionHandler = completionHandler else { return }
+ provider.data { result in
+ switch result {
+ case .success(let data):
+ (options.processingQueue ?? self.processingQueue).execute {
+ let processor = options.processor
+ let processingItem = ImageProcessItem.data(data)
+ guard let image = processor.process(item: processingItem, options: options) else {
+ options.callbackQueue.execute {
+ let error = KingfisherError.processorError(
+ reason: .processingFailed(processor: processor, item: processingItem))
+ completionHandler(.failure(error))
+ }
+ return
+ }
+
+ options.callbackQueue.execute {
+ let result = ImageLoadingResult(image: image, url: nil, originalData: data)
+ completionHandler(.success(result))
+ }
+ }
+ case .failure(let error):
+ options.callbackQueue.execute {
+ let error = KingfisherError.imageSettingError(
+ reason: .dataProviderError(provider: provider, error: error))
+ completionHandler(.failure(error))
+ }
+
+ }
+ }
+ }
+
+ @discardableResult
+ func loadAndCacheImage(
+ source: Source,
+ options: KingfisherParsedOptionsInfo,
+ completionHandler: ((Result) -> Void)?) -> DownloadTask.WrappedTask?
+ {
+ func cacheImage(_ result: Result)
+ {
+ switch result {
+ case .success(let value):
+ // Add image to cache.
+ let targetCache = options.targetCache ?? self.cache
+ targetCache.store(
+ value.image,
+ original: value.originalData,
+ forKey: source.cacheKey,
+ options: options,
+ toDisk: !options.cacheMemoryOnly)
+ {
+ _ in
+ if options.waitForCache {
+ let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source)
+ completionHandler?(.success(result))
+ }
+ }
+
+ // Add original image to cache if necessary.
+ let needToCacheOriginalImage = options.cacheOriginalImage &&
+ options.processor != DefaultImageProcessor.default
+ if needToCacheOriginalImage {
+ let originalCache = options.originalCache ?? targetCache
+ originalCache.storeToDisk(
+ value.originalData,
+ forKey: source.cacheKey,
+ processorIdentifier: DefaultImageProcessor.default.identifier,
+ expiration: options.diskCacheExpiration)
+ }
+
+ if !options.waitForCache {
+ let result = RetrieveImageResult(image: value.image, cacheType: .none, source: source)
+ completionHandler?(.success(result))
+ }
+
+ case .failure(let error):
+ completionHandler?(.failure(error))
+ }
+ }
+
+ switch source {
+ case .network(let resource):
+ let downloader = options.downloader ?? self.downloader
+ guard let task = downloader.downloadImage(
+ with: resource.downloadURL,
+ options: options,
+ completionHandler: cacheImage) else {
+ return nil
+ }
+ return .download(task)
+
+ case .provider(let provider):
+ provideImage(provider: provider, options: options, completionHandler: cacheImage)
+ return .dataProviding
+ }
+ }
+
+ /// Retrieves image from memory or disk cache.
+ ///
+ /// - Parameters:
+ /// - source: The target source from which to get image.
+ /// - key: The key to use when caching the image.
+ /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for
+ /// `RetrieveImageResult` callback compatibility.
+ /// - options: Options on how to get the image from image cache.
+ /// - completionHandler: Called when the image retrieving finishes, either with succeeded
+ /// `RetrieveImageResult` or an error.
+ /// - Returns: `true` if the requested image or the original image before being processed is existing in cache.
+ /// Otherwise, this method returns `false`.
+ ///
+ /// - Note:
+ /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in
+ /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher
+ /// will try to check whether an original version of that image is existing or not. If there is already an
+ /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store
+ /// back to cache for later use.
+ func retrieveImageFromCache(
+ source: Source,
+ options: KingfisherParsedOptionsInfo,
+ completionHandler: ((Result) -> Void)?) -> Bool
+ {
+ // 1. Check whether the image was already in target cache. If so, just get it.
+ let targetCache = options.targetCache ?? cache
+ let key = source.cacheKey
+ let targetImageCached = targetCache.imageCachedType(
+ forKey: key, processorIdentifier: options.processor.identifier)
+
+ let validCache = targetImageCached.cached &&
+ (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory)
+ if validCache {
+ targetCache.retrieveImage(forKey: key, options: options) { result in
+ guard let completionHandler = completionHandler else { return }
+ options.callbackQueue.execute {
+ result.match(
+ onSuccess: { cacheResult in
+ let value: Result
+ if let image = cacheResult.image {
+ value = result.map {
+ RetrieveImageResult(image: image, cacheType: $0.cacheType, source: source)
+ }
+ } else {
+ value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))
+ }
+ completionHandler(value)
+ },
+ onFailure: { _ in
+ completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
+ }
+ )
+ }
+ }
+ return true
+ }
+
+ // 2. Check whether the original image exists. If so, get it, process it, save to storage and return.
+ let originalCache = options.originalCache ?? targetCache
+ // No need to store the same file in the same cache again.
+ if originalCache === targetCache && options.processor == DefaultImageProcessor.default {
+ return false
+ }
+
+ // Check whether the unprocessed image existing or not.
+ let originalImageCached = originalCache.imageCachedType(
+ forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier).cached
+ if originalImageCached {
+ // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove
+ // any processor from options first.
+ var optionsWithoutProcessor = options
+ optionsWithoutProcessor.processor = DefaultImageProcessor.default
+ originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in
+
+ result.match(
+ onSuccess: { cacheResult in
+ guard let image = cacheResult.image else {
+ return
+ }
+
+ let processor = options.processor
+ (options.processingQueue ?? self.processingQueue).execute {
+ let item = ImageProcessItem.image(image)
+ guard let processedImage = processor.process(item: item, options: options) else {
+ let error = KingfisherError.processorError(
+ reason: .processingFailed(processor: processor, item: item))
+ options.callbackQueue.execute { completionHandler?(.failure(error)) }
+ return
+ }
+
+ var cacheOptions = options
+ cacheOptions.callbackQueue = .untouch
+ targetCache.store(
+ processedImage,
+ forKey: key,
+ options: cacheOptions,
+ toDisk: !options.cacheMemoryOnly)
+ {
+ _ in
+ if options.waitForCache {
+ let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source)
+ options.callbackQueue.execute { completionHandler?(.success(value)) }
+ }
+ }
+
+ if !options.waitForCache {
+ let value = RetrieveImageResult(image: processedImage, cacheType: .none, source: source)
+ options.callbackQueue.execute { completionHandler?(.success(value)) }
+ }
+ }
+ },
+ onFailure: { _ in
+ // This should not happen actually, since we already confirmed `originalImageCached` is `true`.
+ // Just in case...
+ options.callbackQueue.execute {
+ completionHandler?(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))))
+ }
+ }
+ )
+ }
+ return true
+ }
+
+ return false
+ }
+}
diff --git a/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
new file mode 100644
index 0000000..f9efb27
--- /dev/null
+++ b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
@@ -0,0 +1,350 @@
+//
+// KingfisherOptionsInfo.swift
+// Kingfisher
+//
+// Created by Wei Wang on 15/4/23.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+
+/// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem].
+/// You can use the enum of option item with value to control some behaviors of Kingfisher.
+public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
+
+extension Array where Element == KingfisherOptionsInfoItem {
+ static let empty: KingfisherOptionsInfo = []
+}
+
+/// Represents the available option items could be used in `KingfisherOptionsInfo`.
+public enum KingfisherOptionsInfoItem {
+
+ /// Kingfisher will use the associated `ImageCache` object when handling related operations,
+ /// including trying to retrieve the cached images and store the downloaded image to it.
+ case targetCache(ImageCache)
+
+ /// The `ImageCache` for storing and retrieving original images. If `originalCache` is
+ /// contained in the options, it will be preferred for storing and retrieving original images.
+ /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
+ ///
+ /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
+ /// applied in the option, the original image will be stored to this `originalCache`. At the
+ /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
+ /// Kingfisher will try to search the original image to check whether it is already there. If found,
+ /// it will be used and applied with the given processor. It is an optimization for not downloading
+ /// the same image for multiple times.
+ case originalCache(ImageCache)
+
+ /// Kingfisher will use the associated `ImageDownloader` object to download the requested images.
+ case downloader(ImageDownloader)
+
+ /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of
+ /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the
+ /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
+ /// the image being retrieved from cache, set `.forceRefresh` as well.
+ case transition(ImageTransition)
+
+ /// Associated `Float` value will be set as the priority of image download task. The value for it should be
+ /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used.
+ case downloadPriority(Float)
+
+ /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource.
+ case forceRefresh
+
+ /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory
+ /// cache, then it will ignore the disk cache but download the image again from network. This is useful when
+ /// you want to display a changeable image behind the same url at the same app session, while avoiding download
+ /// it for multiple times.
+ case fromMemoryCacheOrRefresh
+
+ /// If set, setting the image to an image view will happen with transition even when retrieved from cache.
+ /// See `.transition` option for more.
+ case forceTransition
+
+ /// If set, Kingfisher will only cache the value in memory but not in disk.
+ case cacheMemoryOnly
+
+ /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block.
+ case waitForCache
+
+ /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is
+ /// not in cache, the image retrieving will fail with an error.
+ case onlyFromCache
+
+ /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen
+ /// rendering to extract pixel information in background. This can speed up display, but will cost more time to
+ /// prepare the image for using.
+ case backgroundDecode
+
+ /// The associated value of this member will be used as the target queue of dispatch callbacks when
+ /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks.
+ @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.")
+ case callbackDispatchQueue(DispatchQueue?)
+
+ /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from
+ /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks.
+ ///
+ /// - Note:
+ /// This option does not affect the callbacks for UI related extension methods. You will always get the
+ /// callbacks called from main queue.
+ case callbackQueue(CallbackQueue)
+
+ /// The associated value will be used as the scale factor when converting retrieved data to an image.
+ /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
+ /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
+ case scaleFactor(CGFloat)
+
+ /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames
+ /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory.
+ ///
+ /// This option is mainly used for back compatibility internally. You should not set it directly. Instead,
+ /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher
+ /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but
+ /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once,
+ /// which uses more memory but only decode image frames once.
+ case preloadAllAnimationData
+
+ /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent.
+ /// This is the last chance you can modify the image download request. You can modify the request for some
+ /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
+ /// The original request will be sent without any modification by default.
+ case requestModifier(ImageDownloadRequestModifier)
+
+ /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection.
+ /// This is the posibility you can modify the image download request during redirect. You can modify the request for
+ /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
+ /// mapping.
+ /// The original redirection request will be sent without any modification by default.
+ case redirectHandler(ImageDownloadRedirectHandler)
+
+ /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
+ /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using
+ /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well.
+ /// If not set, the `DefaultImageProcessor.default` will be used.
+ case processor(ImageProcessor)
+
+ /// Supplies a `CacheSerializer` to convert some data to an image object for
+ /// retrieving from disk cache or vice versa for storing to disk cache.
+ /// If not set, the `DefaultCacheSerializer.default` will be used.
+ case cacheSerializer(CacheSerializer)
+
+ /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched
+ /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being
+ /// fetched from a cache, the modifier will run after the `CacheSerializer`.
+ ///
+ /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete
+ /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`.
+ case imageModifier(ImageModifier)
+
+ /// Keep the existing image of image view while setting another image to it.
+ /// By setting this option, the placeholder image parameter of image view extension method
+ /// will be ignored and the current image will be kept while loading or downloading the new image.
+ case keepCurrentImageWhileLoading
+
+ /// If set, Kingfisher will only load the first frame from an animated image file as a single image.
+ /// Loading an animated images may take too much memory. It will be useful when you want to display a
+ /// static preview of the first frame from a animated image.
+ ///
+ /// This option will be ignored if the target image is not animated image data.
+ case onlyLoadFirstFrame
+
+ /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
+ /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
+ /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
+ /// images if necessary.
+ ///
+ /// The original image will be only cached to disk storage.
+ case cacheOriginalImage
+
+ /// If set and a downloading error occurred Kingfisher will set provided image (or empty)
+ /// in place of requested one. It's useful when you don't want to show placeholder
+ /// during loading time but wants to use some default image when requests will be failed.
+ case onFailureImage(Image?)
+
+ /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage
+ /// aggressively. By default this is not contained in the options, that means if the requested image is already
+ /// in disk cache, Kingfisher will not try to load it to memory.
+ case alsoPrefetchToMemory
+
+ /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading
+ /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
+ /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
+ /// has an image set.
+ ///
+ /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
+ /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
+ case loadDiskFileSynchronously
+
+ /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the
+ /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated
+ /// value to overwrite the config setting for this caching item.
+ case memoryCacheExpiration(StorageExpiration)
+
+ /// The expiration extending setting for memory cache. The item expiration time will be incremented by this value after access.
+ /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending value: .cacheTime.
+ /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options.
+ case memoryCacheAccessExtendingExpiration(ExpirationExtending)
+
+ /// The expiration setting for memory cache. By default, the underlying `DiskStorage.Backend` uses the
+ /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated
+ /// value to overwrite the config setting for this caching item.
+ case diskCacheExpiration(StorageExpiration)
+
+ /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial
+ /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
+ /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
+ /// blocking the UI, especially if the processor needs a lot of time to run).
+ case processingQueue(CallbackQueue)
+
+ /// Enable progressive image loading, Kingfisher will use the `ImageProgressive` of
+ case progressiveJPEG(ImageProgressive)
+}
+
+// Improve performance by parsing the input `KingfisherOptionsInfo` (self) first.
+// So we can prevent the iterating over the options array again and again.
+/// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member
+/// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be
+/// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods.
+public struct KingfisherParsedOptionsInfo {
+
+ public var targetCache: ImageCache? = nil
+ public var originalCache: ImageCache? = nil
+ public var downloader: ImageDownloader? = nil
+ public var transition: ImageTransition = .none
+ public var downloadPriority: Float = URLSessionTask.defaultPriority
+ public var forceRefresh = false
+ public var fromMemoryCacheOrRefresh = false
+ public var forceTransition = false
+ public var cacheMemoryOnly = false
+ public var waitForCache = false
+ public var onlyFromCache = false
+ public var backgroundDecode = false
+ public var preloadAllAnimationData = false
+ public var callbackQueue: CallbackQueue = .mainCurrentOrAsync
+ public var scaleFactor: CGFloat = 1.0
+ public var requestModifier: ImageDownloadRequestModifier? = nil
+ public var redirectHandler: ImageDownloadRedirectHandler? = nil
+ public var processor: ImageProcessor = DefaultImageProcessor.default
+ public var imageModifier: ImageModifier? = nil
+ public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default
+ public var keepCurrentImageWhileLoading = false
+ public var onlyLoadFirstFrame = false
+ public var cacheOriginalImage = false
+ public var onFailureImage: Optional = .none
+ public var alsoPrefetchToMemory = false
+ public var loadDiskFileSynchronously = false
+ public var memoryCacheExpiration: StorageExpiration? = nil
+ public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime
+ public var diskCacheExpiration: StorageExpiration? = nil
+ public var processingQueue: CallbackQueue? = nil
+ public var progressiveJPEG: ImageProgressive? = nil
+
+ var onDataReceived: [DataReceivingSideEffect]? = nil
+
+ public init(_ info: KingfisherOptionsInfo?) {
+ guard let info = info else { return }
+ for option in info {
+ switch option {
+ case .targetCache(let value): targetCache = value
+ case .originalCache(let value): originalCache = value
+ case .downloader(let value): downloader = value
+ case .transition(let value): transition = value
+ case .downloadPriority(let value): downloadPriority = value
+ case .forceRefresh: forceRefresh = true
+ case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true
+ case .forceTransition: forceTransition = true
+ case .cacheMemoryOnly: cacheMemoryOnly = true
+ case .waitForCache: waitForCache = true
+ case .onlyFromCache: onlyFromCache = true
+ case .backgroundDecode: backgroundDecode = true
+ case .preloadAllAnimationData: preloadAllAnimationData = true
+ case .callbackQueue(let value): callbackQueue = value
+ case .scaleFactor(let value): scaleFactor = value
+ case .requestModifier(let value): requestModifier = value
+ case .redirectHandler(let value): redirectHandler = value
+ case .processor(let value): processor = value
+ case .imageModifier(let value): imageModifier = value
+ case .cacheSerializer(let value): cacheSerializer = value
+ case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true
+ case .onlyLoadFirstFrame: onlyLoadFirstFrame = true
+ case .cacheOriginalImage: cacheOriginalImage = true
+ case .onFailureImage(let value): onFailureImage = .some(value)
+ case .alsoPrefetchToMemory: alsoPrefetchToMemory = true
+ case .loadDiskFileSynchronously: loadDiskFileSynchronously = true
+ case .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync
+ case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration
+ case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending
+ case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration
+ case .processingQueue(let queue): processingQueue = queue
+ case .progressiveJPEG(let value): progressiveJPEG = value
+ }
+ }
+
+ if originalCache == nil {
+ originalCache = targetCache
+ }
+ }
+}
+
+extension KingfisherParsedOptionsInfo {
+ var imageCreatingOptions: ImageCreatingOptions {
+ return ImageCreatingOptions(
+ scale: scaleFactor,
+ duration: 0.0,
+ preloadAll: preloadAllAnimationData,
+ onlyFirstFrame: onlyLoadFirstFrame)
+ }
+}
+
+protocol DataReceivingSideEffect: AnyObject {
+ var onShouldApply: () -> Bool { get set }
+ func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data)
+}
+
+class ImageLoadingProgressSideEffect: DataReceivingSideEffect {
+
+ var onShouldApply: () -> Bool = { return true }
+
+ let block: DownloadProgressBlock
+
+ init(_ block: @escaping DownloadProgressBlock) {
+ self.block = block
+ }
+
+ func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) {
+ guard onShouldApply() else { return }
+ guard
+ let expectedContentLength = task.task.response?.expectedContentLength,
+ expectedContentLength != -1 else {
+ return
+ }
+
+ let dataLength = Int64(task.mutableData.count)
+ DispatchQueue.main.async {
+ self.block(dataLength, expectedContentLength)
+ }
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Image/Filter.swift b/Pods/Kingfisher/Sources/Image/Filter.swift
new file mode 100644
index 0000000..e93bc8b
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/Filter.swift
@@ -0,0 +1,142 @@
+//
+// Filter.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2016/08/31.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 CoreImage
+
+// Reuse the same CI Context for all CI drawing.
+private let ciContext = CIContext(options: nil)
+
+/// Represents the type of transformer method, which will be used in to provide a `Filter`.
+public typealias Transformer = (CIImage) -> CIImage?
+
+/// Represents a processor based on a `CIImage` `Filter`.
+/// It requires a filter to create an `ImageProcessor`.
+public protocol CIImageProcessor: ImageProcessor {
+ var filter: Filter { get }
+}
+
+extension CIImageProcessor {
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.apply(filter)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// A wrapper struct for a `Transformer` of CIImage filters. A `Filter`
+/// value could be used to create a `CIImage` processor.
+public struct Filter {
+
+ let transform: Transformer
+
+ public init(transform: @escaping Transformer) {
+ self.transform = transform
+ }
+
+ /// Tint filter which will apply a tint color to images.
+ public static var tint: (Color) -> Filter = {
+ color in
+ Filter {
+ input in
+
+ let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
+ colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
+
+ let filter = CIFilter(name: "CISourceOverCompositing")!
+
+ let colorImage = colorFilter.outputImage
+ filter.setValue(colorImage, forKey: kCIInputImageKey)
+ filter.setValue(input, forKey: kCIInputBackgroundImageKey)
+
+ return filter.outputImage?.cropped(to: input.extent)
+ }
+ }
+
+ /// Represents color control elements. It is a tuple of
+ /// `(brightness, contrast, saturation, inputEV)`
+ public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
+
+ /// Color control filter which will apply color control change to images.
+ public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in
+ let (brightness, contrast, saturation, inputEV) = arg
+ return Filter { input in
+ let paramsColor = [kCIInputBrightnessKey: brightness,
+ kCIInputContrastKey: contrast,
+ kCIInputSaturationKey: saturation]
+ let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor)
+ let paramsExposure = [kCIInputEVKey: inputEV]
+ return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure)
+ }
+ }
+}
+
+extension KingfisherWrapper where Base: Image {
+
+ /// Applies a `Filter` containing `CIImage` transformer to `self`.
+ ///
+ /// - Parameter filter: The filter used to transform `self`.
+ /// - Returns: A transformed image by input `Filter`.
+ ///
+ /// - Note:
+ /// Only CG-based images are supported. If any error happens
+ /// during transforming, `self` will be returned.
+ public func apply(_ filter: Filter) -> Image {
+
+ guard let cgImage = cgImage else {
+ assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
+ return base
+ }
+
+ let inputImage = CIImage(cgImage: cgImage)
+ guard let outputImage = filter.transform(inputImage) else {
+ return base
+ }
+
+ guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
+ assertionFailure("[Kingfisher] Can not make an tint image within context.")
+ return base
+ }
+
+ #if os(macOS)
+ return fixedForRetinaPixel(cgImage: result, to: size)
+ #else
+ return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
+ #endif
+ }
+
+}
diff --git a/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift
new file mode 100644
index 0000000..fd2f443
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift
@@ -0,0 +1,121 @@
+//
+// AnimatedImage.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/09/26.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 ImageIO
+
+/// Represents a set of image creating options used in Kingfisher.
+public struct ImageCreatingOptions {
+
+ /// The target scale of image needs to be created.
+ public let scale: CGFloat
+
+ /// The expected animation duration if an animated image being created.
+ public let duration: TimeInterval
+
+ /// For an animated image, whether or not all frames should be loaded before displaying.
+ public let preloadAll: Bool
+
+ /// For an animated image, whether or not only the first image should be
+ /// loaded as a static image. It is useful for preview purpose of an animated image.
+ public let onlyFirstFrame: Bool
+
+ /// Creates an `ImageCreatingOptions` object.
+ ///
+ /// - Parameters:
+ /// - scale: The target scale of image needs to be created. Default is `1.0`.
+ /// - duration: The expected animation duration if an animated image being created.
+ /// A value less or equal to `0.0` means the animated image duration will
+ /// be determined by the frame data. Default is `0.0`.
+ /// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying.
+ /// Default is `false`.
+ /// - onlyFirstFrame: For an animated image, whether or not only the first image should be
+ /// loaded as a static image. It is useful for preview purpose of an animated image.
+ /// Default is `false`.
+ public init(
+ scale: CGFloat = 1.0,
+ duration: TimeInterval = 0.0,
+ preloadAll: Bool = false,
+ onlyFirstFrame: Bool = false)
+ {
+ self.scale = scale
+ self.duration = duration
+ self.preloadAll = preloadAll
+ self.onlyFirstFrame = onlyFirstFrame
+ }
+}
+
+// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then
+// hold the images for later use.
+class GIFAnimatedImage {
+ let images: [Image]
+ let duration: TimeInterval
+
+ init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) {
+ let frameCount = CGImageSourceGetCount(imageSource)
+ var images = [Image]()
+ var gifDuration = 0.0
+
+ for i in 0 ..< frameCount {
+ guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else {
+ return nil
+ }
+
+ if frameCount == 1 {
+ gifDuration = .infinity
+ } else {
+ // Get current animated GIF frame duration
+ gifDuration += GIFAnimatedImage.getFrameDuration(from: imageSource, at: i)
+ }
+ images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil))
+ if options.onlyFirstFrame { break }
+ }
+ self.images = images
+ self.duration = gifDuration
+ }
+
+ // Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary.
+ static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval {
+ let defaultFrameDuration = 0.1
+ guard let gifInfo = gifInfo else { return defaultFrameDuration }
+
+ let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber
+ let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber
+ let duration = unclampedDelayTime ?? delayTime
+
+ guard let frameDuration = duration else { return defaultFrameDuration }
+ return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration
+ }
+
+ // Calculates frame duration at a specific index for a gif from an `imageSource`.
+ static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval {
+ guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil)
+ as? [String: Any] else { return 0.0 }
+
+ let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any]
+ return getFrameDuration(from: gifInfo)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Image/Image.swift b/Pods/Kingfisher/Sources/Image/Image.swift
new file mode 100644
index 0000000..d1ae4f7
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/Image.swift
@@ -0,0 +1,367 @@
+//
+// Image.swift
+// Kingfisher
+//
+// Created by Wei Wang on 16/1/6.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+private var imagesKey: Void?
+private var durationKey: Void?
+#else
+import UIKit
+import MobileCoreServices
+private var imageSourceKey: Void?
+#endif
+
+#if !os(watchOS)
+import CoreImage
+#endif
+
+import CoreGraphics
+import ImageIO
+
+private var animatedImageDataKey: Void?
+
+// MARK: - Image Properties
+extension KingfisherWrapper where Base: Image {
+ private(set) var animatedImageData: Data? {
+ get { return getAssociatedObject(base, &animatedImageDataKey) }
+ set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) }
+ }
+
+ #if os(macOS)
+ var cgImage: CGImage? {
+ return base.cgImage(forProposedRect: nil, context: nil, hints: nil)
+ }
+
+ var scale: CGFloat {
+ return 1.0
+ }
+
+ private(set) var images: [Image]? {
+ get { return getAssociatedObject(base, &imagesKey) }
+ set { setRetainedAssociatedObject(base, &imagesKey, newValue) }
+ }
+
+ private(set) var duration: TimeInterval {
+ get { return getAssociatedObject(base, &durationKey) ?? 0.0 }
+ set { setRetainedAssociatedObject(base, &durationKey, newValue) }
+ }
+
+ var size: CGSize {
+ return base.representations.reduce(.zero) { size, rep in
+ let width = max(size.width, CGFloat(rep.pixelsWide))
+ let height = max(size.height, CGFloat(rep.pixelsHigh))
+ return CGSize(width: width, height: height)
+ }
+ }
+ #else
+ var cgImage: CGImage? { return base.cgImage }
+ var scale: CGFloat { return base.scale }
+ var images: [Image]? { return base.images }
+ var duration: TimeInterval { return base.duration }
+ var size: CGSize { return base.size }
+
+ private(set) var imageSource: CGImageSource? {
+ get { return getAssociatedObject(base, &imageSourceKey) }
+ set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) }
+ }
+ #endif
+
+ // Bitmap memory cost with bytes.
+ var cost: Int {
+ let pixel = Int(size.width * size.height * scale * scale)
+ guard let cgImage = cgImage else {
+ return pixel * 4
+ }
+ return pixel * cgImage.bitsPerPixel / 8
+ }
+}
+
+// MARK: - Image Conversion
+extension KingfisherWrapper where Base: Image {
+ #if os(macOS)
+ static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
+ return Image(cgImage: cgImage, size: .zero)
+ }
+
+ /// Normalize the image. This getter does nothing on macOS but return the image itself.
+ public var normalized: Image { return base }
+
+ #else
+ /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for
+ /// compatibility of macOS version.
+ static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image {
+ return Image(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up)
+ }
+
+ /// Returns normalized image for current `base` image.
+ /// This method will try to redraw an image with orientation and scale considered.
+ public var normalized: Image {
+ // prevent animated image (GIF) lose it's images
+ guard images == nil else { return base.copy() as! Image }
+ // No need to do anything if already up
+ guard base.imageOrientation != .up else { return base.copy() as! Image }
+
+ return draw(to: size, inverting: true, refImage: Image()) {
+ fixOrientation(in: $0)
+ }
+ }
+
+ func fixOrientation(in context: CGContext) {
+
+ var transform = CGAffineTransform.identity
+
+ let orientation = base.imageOrientation
+
+ switch orientation {
+ case .down, .downMirrored:
+ transform = transform.translatedBy(x: size.width, y: size.height)
+ transform = transform.rotated(by: .pi)
+ case .left, .leftMirrored:
+ transform = transform.translatedBy(x: size.width, y: 0)
+ transform = transform.rotated(by: .pi / 2.0)
+ case .right, .rightMirrored:
+ transform = transform.translatedBy(x: 0, y: size.height)
+ transform = transform.rotated(by: .pi / -2.0)
+ case .up, .upMirrored:
+ break
+ #if compiler(>=5)
+ @unknown default:
+ break
+ #endif
+ }
+
+ //Flip image one more time if needed to, this is to prevent flipped image
+ switch orientation {
+ case .upMirrored, .downMirrored:
+ transform = transform.translatedBy(x: size.width, y: 0)
+ transform = transform.scaledBy(x: -1, y: 1)
+ case .leftMirrored, .rightMirrored:
+ transform = transform.translatedBy(x: size.height, y: 0)
+ transform = transform.scaledBy(x: -1, y: 1)
+ case .up, .down, .left, .right:
+ break
+ #if compiler(>=5)
+ @unknown default:
+ break
+ #endif
+ }
+
+ context.concatenate(transform)
+ switch orientation {
+ case .left, .leftMirrored, .right, .rightMirrored:
+ context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
+ default:
+ context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
+ }
+ }
+ #endif
+}
+
+// MARK: - Image Representation
+extension KingfisherWrapper where Base: Image {
+ /// Returns PNG representation of `base` image.
+ ///
+ /// - Returns: PNG data of image.
+ public func pngRepresentation() -> Data? {
+ #if os(macOS)
+ guard let cgImage = cgImage else {
+ return nil
+ }
+ let rep = NSBitmapImageRep(cgImage: cgImage)
+ return rep.representation(using: .png, properties: [:])
+ #else
+ #if swift(>=4.2)
+ return base.pngData()
+ #else
+ return UIImagePNGRepresentation(base)
+ #endif
+ #endif
+ }
+
+ /// Returns JPEG representation of `base` image.
+ ///
+ /// - Parameter compressionQuality: The compression quality when converting image to JPEG data.
+ /// - Returns: JPEG data of image.
+ public func jpegRepresentation(compressionQuality: CGFloat) -> Data? {
+ #if os(macOS)
+ guard let cgImage = cgImage else {
+ return nil
+ }
+ let rep = NSBitmapImageRep(cgImage: cgImage)
+ return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality])
+ #else
+ #if swift(>=4.2)
+ return base.jpegData(compressionQuality: compressionQuality)
+ #else
+ return UIImageJPEGRepresentation(base, compressionQuality)
+ #endif
+ #endif
+ }
+
+ /// Returns GIF representation of `base` image.
+ ///
+ /// - Returns: Original GIF data of image.
+ public func gifRepresentation() -> Data? {
+ return animatedImageData
+ }
+
+ /// Returns a data representation for `base` image, with the `format` as the format indicator.
+ ///
+ /// - Parameter format: The format in which the output data should be. If `unknown`, the `base` image will be
+ /// converted in the PNG representation.
+ /// - Returns: The output data representing.
+ public func data(format: ImageFormat) -> Data? {
+ let data: Data?
+ switch format {
+ case .PNG: data = pngRepresentation()
+ case .JPEG: data = jpegRepresentation(compressionQuality: 1.0)
+ case .GIF: data = gifRepresentation()
+ case .unknown: data = normalized.kf.pngRepresentation()
+ }
+
+ return data
+ }
+}
+
+// MARK: - Creating Images
+extension KingfisherWrapper where Base: Image {
+
+ /// Creates an animated image from a given data and options. Currently only GIF data is supported.
+ ///
+ /// - Parameters:
+ /// - data: The animated image data.
+ /// - options: Options to use when creating the animated image.
+ /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a
+ /// certain duration. `nil` if anything wrong when creating animated image.
+ public static func animatedImage(data: Data, options: ImageCreatingOptions) -> Image? {
+ let info: [String: Any] = [
+ kCGImageSourceShouldCache as String: true,
+ kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF
+ ]
+
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else {
+ return nil
+ }
+
+ #if os(macOS)
+ guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
+ return nil
+ }
+ var image: Image?
+ if options.onlyFirstFrame {
+ image = animatedImage.images.first
+ } else {
+ image = Image(data: data)
+ var kf = image?.kf
+ kf?.images = animatedImage.images
+ kf?.duration = animatedImage.duration
+ }
+ image?.kf.animatedImageData = data
+ return image
+ #else
+
+ var image: Image?
+ if options.preloadAll || options.onlyFirstFrame {
+ // Use `images` image if you want to preload all animated data
+ guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else {
+ return nil
+ }
+ if options.onlyFirstFrame {
+ image = animatedImage.images.first
+ } else {
+ let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration
+ image = .animatedImage(with: animatedImage.images, duration: duration)
+ }
+ image?.kf.animatedImageData = data
+ } else {
+ image = Image(data: data, scale: options.scale)
+ var kf = image?.kf
+ kf?.imageSource = imageSource
+ kf?.animatedImageData = data
+ }
+
+ return image
+ #endif
+ }
+
+ /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other
+ /// image format, image initializer from system will be used. If no image object could be created from
+ /// the given `data`, `nil` will be returned.
+ ///
+ /// - Parameters:
+ /// - data: The image data representation.
+ /// - options: Options to use when creating the image.
+ /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil`
+ /// will be returned.
+ public static func image(data: Data, options: ImageCreatingOptions) -> Image? {
+ var image: Image?
+ switch data.kf.imageFormat {
+ case .JPEG:
+ image = Image(data: data, scale: options.scale)
+ case .PNG:
+ image = Image(data: data, scale: options.scale)
+ case .GIF:
+ image = KingfisherWrapper.animatedImage(data: data, options: options)
+ case .unknown:
+ image = Image(data: data, scale: options.scale)
+ }
+ return image
+ }
+
+ /// Creates a downsampled image from given data to a certain size and scale.
+ ///
+ /// - Parameters:
+ /// - data: The image data contains a JPEG or PNG image.
+ /// - pointSize: The target size in point to which the image should be downsampled.
+ /// - scale: The scale of result image.
+ /// - Returns: A downsampled `Image` object following the input conditions.
+ ///
+ /// - Note:
+ /// Different from image `resize` methods, downsampling will not render the original
+ /// input image in pixel format. It does downsampling from the image data, so it is much
+ /// more memory efficient and friendly. Choose to use downsampling as possible as you can.
+ ///
+ /// The input size should be smaller than the size of input image. If it is larger than the
+ /// original image size, the result image will be the same size of input without downsampling.
+ public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> Image? {
+ let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
+ guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else {
+ return nil
+ }
+
+ let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale
+ let downsampleOptions = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
+ guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
+ return nil
+ }
+ return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Image/ImageDrawing.swift b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift
new file mode 100644
index 0000000..29daf20
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift
@@ -0,0 +1,529 @@
+//
+// ImageDrawing.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/09/28.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 Accelerate
+
+#if canImport(AppKit)
+import AppKit
+#endif
+#if canImport(UIKit)
+import UIKit
+#endif
+
+// MARK: - Image Transforming
+extension KingfisherWrapper where Base: Image {
+ // MARK: Blend Mode
+ /// Create image from `base` image and apply blend mode.
+ ///
+ /// - parameter blendMode: The blend mode of creating image.
+ /// - parameter alpha: The alpha should be used for image.
+ /// - parameter backgroundColor: The background color for the output image.
+ ///
+ /// - returns: An image with blend mode applied.
+ ///
+ /// - Note: This method only works for CG-based image.
+ #if !os(macOS)
+ public func image(withBlendMode blendMode: CGBlendMode,
+ alpha: CGFloat = 1.0,
+ backgroundColor: Color? = nil) -> Image
+ {
+ guard let _ = cgImage else {
+ assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
+ return base
+ }
+
+ let rect = CGRect(origin: .zero, size: size)
+ return draw(to: rect.size) { _ in
+ if let backgroundColor = backgroundColor {
+ backgroundColor.setFill()
+ UIRectFill(rect)
+ }
+
+ base.draw(in: rect, blendMode: blendMode, alpha: alpha)
+ }
+ }
+ #endif
+
+ #if os(macOS)
+ // MARK: Compositing
+ /// Creates image from `base` image and apply compositing operation.
+ ///
+ /// - Parameters:
+ /// - compositingOperation: The compositing operation of creating image.
+ /// - alpha: The alpha should be used for image.
+ /// - backgroundColor: The background color for the output image.
+ /// - Returns: An image with compositing operation applied.
+ ///
+ /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned.
+ public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
+ alpha: CGFloat = 1.0,
+ backgroundColor: Color? = nil) -> Image
+ {
+ guard let _ = cgImage else {
+ assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
+ return base
+ }
+
+ let rect = CGRect(origin: .zero, size: size)
+ return draw(to: rect.size) { _ in
+ if let backgroundColor = backgroundColor {
+ backgroundColor.setFill()
+ rect.fill()
+ }
+ base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
+ }
+ }
+ #endif
+
+ // MARK: Round Corner
+ /// Creates a round corner image from on `base` image.
+ ///
+ /// - Parameters:
+ /// - radius: The round corner radius of creating image.
+ /// - size: The target size of creating image.
+ /// - corners: The target corners which will be applied rounding.
+ /// - backgroundColor: The background color for the output image
+ /// - Returns: An image with round corner of `self`.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func image(withRoundRadius radius: CGFloat,
+ fit size: CGSize,
+ roundingCorners corners: RectCorner = .all,
+ backgroundColor: Color? = nil) -> Image
+ {
+ guard let _ = cgImage else {
+ assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
+ return base
+ }
+
+ let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+ return draw(to: size) { _ in
+ #if os(macOS)
+ if let backgroundColor = backgroundColor {
+ let rectPath = NSBezierPath(rect: rect)
+ backgroundColor.setFill()
+ rectPath.fill()
+ }
+
+ let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
+ #if swift(>=4.2)
+ path.windingRule = .evenOdd
+ #else
+ path.windingRule = .evenOddWindingRule
+ #endif
+ path.addClip()
+ base.draw(in: rect)
+ #else
+ guard let context = UIGraphicsGetCurrentContext() else {
+ assertionFailure("[Kingfisher] Failed to create CG context for image.")
+ return
+ }
+
+ if let backgroundColor = backgroundColor {
+ let rectPath = UIBezierPath(rect: rect)
+ backgroundColor.setFill()
+ rectPath.fill()
+ }
+
+ let path = UIBezierPath(
+ roundedRect: rect,
+ byRoundingCorners: corners.uiRectCorner,
+ cornerRadii: CGSize(width: radius, height: radius)
+ )
+ context.addPath(path.cgPath)
+ context.clip()
+ base.draw(in: rect)
+ #endif
+ }
+ }
+
+ #if os(iOS) || os(tvOS)
+ func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> Image {
+ switch contentMode {
+ case .scaleAspectFit:
+ return resize(to: size, for: .aspectFit)
+ case .scaleAspectFill:
+ return resize(to: size, for: .aspectFill)
+ default:
+ return resize(to: size)
+ }
+ }
+ #endif
+
+ // MARK: Resizing
+ /// Resizes `base` image to an image with new size.
+ ///
+ /// - Parameter size: The target size in point.
+ /// - Returns: An image with new size.
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func resize(to size: CGSize) -> Image {
+ guard let _ = cgImage else {
+ assertionFailure("[Kingfisher] Resize only works for CG-based image.")
+ return base
+ }
+
+ let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+ return draw(to: size) { _ in
+ #if os(macOS)
+ base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
+ #else
+ base.draw(in: rect)
+ #endif
+ }
+ }
+
+ /// Resizes `base` image to an image of new size, respecting the given content mode.
+ ///
+ /// - Parameters:
+ /// - targetSize: The target size in point.
+ /// - contentMode: Content mode of output image should be.
+ /// - Returns: An image with new size.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> Image {
+ let newSize = size.kf.resize(to: targetSize, for: contentMode)
+ return resize(to: newSize)
+ }
+
+ // MARK: Cropping
+ /// Crops `base` image to a new size with a given anchor.
+ ///
+ /// - Parameters:
+ /// - size: The target size.
+ /// - anchor: The anchor point from which the size should be calculated.
+ /// - Returns: An image with new size.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
+ guard let cgImage = cgImage else {
+ assertionFailure("[Kingfisher] Crop only works for CG-based image.")
+ return base
+ }
+
+ let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
+ guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
+ assertionFailure("[Kingfisher] Cropping image failed.")
+ return base
+ }
+
+ return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
+ }
+
+ // MARK: Blur
+ /// Creates an image with blur effect based on `base` image.
+ ///
+ /// - Parameter radius: The blur radius should be used when creating blur effect.
+ /// - Returns: An image with blur effect applied.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func blurred(withRadius radius: CGFloat) -> Image {
+
+ guard let cgImage = cgImage else {
+ assertionFailure("[Kingfisher] Blur only works for CG-based image.")
+ return base
+ }
+
+ // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
+ // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
+ // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
+ let s = Float(max(radius, 2.0))
+ // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
+
+ // Fix the slow compiling time for Swift 3.
+ // See https://github.com/onevcat/Kingfisher/issues/611
+ let pi2 = 2 * Float.pi
+ let sqrtPi2 = sqrt(pi2)
+ var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
+
+ if targetRadius.isEven { targetRadius += 1 }
+
+ // Determine necessary iteration count by blur radius.
+ let iterations: Int
+ if radius < 0.5 {
+ iterations = 1
+ } else if radius < 1.5 {
+ iterations = 2
+ } else {
+ iterations = 3
+ }
+
+ let w = Int(size.width)
+ let h = Int(size.height)
+ let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
+
+ func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
+ let data = context.data
+ let width = vImagePixelCount(context.width)
+ let height = vImagePixelCount(context.height)
+ let rowBytes = context.bytesPerRow
+
+ return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
+ }
+
+ guard let context = beginContext(size: size, scale: scale, inverting: true) else {
+ assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+ return base
+ }
+ context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
+ endContext()
+
+ var inBuffer = createEffectBuffer(context)
+
+ guard let outContext = beginContext(size: size, scale: scale, inverting: true) else {
+ assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+ return base
+ }
+ defer { endContext() }
+ var outBuffer = createEffectBuffer(outContext)
+
+ for _ in 0 ..< iterations {
+ let flag = vImage_Flags(kvImageEdgeExtend)
+ vImageBoxConvolve_ARGB8888(
+ &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
+ // Next inBuffer should be the outButter of current iteration
+ (inBuffer, outBuffer) = (outBuffer, inBuffer)
+ }
+
+ #if os(macOS)
+ let result = outContext.makeImage().flatMap {
+ fixedForRetinaPixel(cgImage: $0, to: size)
+ }
+ #else
+ let result = outContext.makeImage().flatMap {
+ Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
+ }
+ #endif
+ guard let blurredImage = result else {
+ assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
+ return base
+ }
+
+ return blurredImage
+ }
+
+ // MARK: Overlay
+ /// Creates an image from `base` image with a color overlay layer.
+ ///
+ /// - Parameters:
+ /// - color: The color should be use to overlay.
+ /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
+ /// 1.0 means transparent overlay.
+ /// - Returns: An image with a color overlay applied.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image, `base` itself is returned.
+ public func overlaying(with color: Color, fraction: CGFloat) -> Image {
+
+ guard let _ = cgImage else {
+ assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
+ return base
+ }
+
+ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
+ return draw(to: rect.size) { context in
+ #if os(macOS)
+ base.draw(in: rect)
+ if fraction > 0 {
+ color.withAlphaComponent(1 - fraction).set()
+ rect.fill(using: .sourceAtop)
+ }
+ #else
+ color.set()
+ UIRectFill(rect)
+ base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
+
+ if fraction > 0 {
+ base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
+ }
+ #endif
+ }
+ }
+
+ // MARK: Tint
+ /// Creates an image from `base` image with a color tint.
+ ///
+ /// - Parameter color: The color should be used to tint `base`
+ /// - Returns: An image with a color tint applied.
+ public func tinted(with color: Color) -> Image {
+ #if os(watchOS)
+ return base
+ #else
+ return apply(.tint(color))
+ #endif
+ }
+
+ // MARK: Color Control
+
+ /// Create an image from `self` with color control.
+ ///
+ /// - Parameters:
+ /// - brightness: Brightness changing to image.
+ /// - contrast: Contrast changing to image.
+ /// - saturation: Saturation changing to image.
+ /// - inputEV: InputEV changing to image.
+ /// - Returns: An image with color control applied.
+ public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
+ #if os(watchOS)
+ return base
+ #else
+ return apply(.colorControl((brightness, contrast, saturation, inputEV)))
+ #endif
+ }
+
+ /// Return an image with given scale.
+ ///
+ /// - Parameter scale: Target scale factor the new image should have.
+ /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
+ public func scaled(to scale: CGFloat) -> Image {
+ guard scale != self.scale else {
+ return base
+ }
+ guard let cgImage = cgImage else {
+ assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
+ return base
+ }
+ return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
+ }
+}
+
+// MARK: - Decoding Image
+extension KingfisherWrapper where Base: Image {
+
+ /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
+ /// from it. This could improve the drawing performance when an image is just created from data but not yet
+ /// displayed for the first time.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image or animated image, `base` itself is returned.
+ public var decoded: Image { return decoded(scale: scale) }
+
+ /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
+ /// return the data from it. This could improve the drawing performance when an image is just created from
+ /// data but not yet displayed for the first time.
+ ///
+ /// - Parameter scale: The given scale of target image should be.
+ /// - Returns: The decoded image ready to be displayed.
+ ///
+ /// - Note: This method only works for CG-based image. The current image scale is kept.
+ /// For any non-CG-based image or animated image, `base` itself is returned.
+ public func decoded(scale: CGFloat) -> Image {
+ // Prevent animated image (GIF) losing it's images
+ #if os(iOS)
+ if imageSource != nil { return base }
+ #else
+ if images != nil { return base }
+ #endif
+
+ guard let imageRef = cgImage else {
+ assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
+ return base
+ }
+
+ let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
+ return draw(to: size, inverting: true, scale: scale) { context in
+ context.draw(imageRef, in: CGRect(origin: .zero, size: size))
+ }
+ }
+}
+
+extension KingfisherWrapper where Base: Image {
+
+ func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? {
+ #if os(macOS)
+ guard let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: Int(size.width),
+ pixelsHigh: Int(size.height),
+ bitsPerSample: cgImage?.bitsPerComponent ?? 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .calibratedRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0) else
+ {
+ assertionFailure("[Kingfisher] Image representation cannot be created.")
+ return nil
+ }
+ rep.size = size
+ NSGraphicsContext.saveGraphicsState()
+ guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
+ assertionFailure("[Kingfisher] Image context cannot be created.")
+ return nil
+ }
+
+ NSGraphicsContext.current = context
+ return context.cgContext
+ #else
+ UIGraphicsBeginImageContextWithOptions(size, false, scale)
+ guard let context = UIGraphicsGetCurrentContext() else { return nil }
+ if inverting { // If drawing a CGImage, we need to make context flipped.
+ context.scaleBy(x: 1.0, y: -1.0)
+ context.translateBy(x: 0, y: -size.height)
+ }
+ return context
+ #endif
+ }
+
+ func endContext() {
+ #if os(macOS)
+ NSGraphicsContext.restoreGraphicsState()
+ #else
+ UIGraphicsEndImageContext()
+ #endif
+ }
+
+ func draw(to size: CGSize, inverting: Bool = false, scale: CGFloat? = nil, refImage: Image? = nil, draw: (CGContext) -> Void) -> Image {
+ let targetScale = scale ?? self.scale
+ guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else {
+ assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
+ return base
+ }
+ defer { endContext() }
+ draw(context)
+ guard let cgImage = context.makeImage() else {
+ return base
+ }
+ return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: refImage ?? base)
+ }
+
+ #if os(macOS)
+ func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
+
+ let image = Image(cgImage: cgImage, size: base.size)
+ let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
+
+ return draw(to: self.size) { context in
+ image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
+ }
+ }
+ #endif
+}
diff --git a/Pods/Kingfisher/Sources/Image/ImageFormat.swift b/Pods/Kingfisher/Sources/Image/ImageFormat.swift
new file mode 100644
index 0000000..14e3c7d
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/ImageFormat.swift
@@ -0,0 +1,131 @@
+//
+// ImageFormat.swift
+// Kingfisher
+//
+// Created by onevcat on 2018/09/28.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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 image format.
+///
+/// - unknown: The format cannot be recognized or not supported yet.
+/// - PNG: PNG image format.
+/// - JPEG: JPEG image format.
+/// - GIF: GIF image format.
+public enum ImageFormat {
+ /// The format cannot be recognized or not supported yet.
+ case unknown
+ /// PNG image format.
+ case PNG
+ /// JPEG image format.
+ case JPEG
+ /// GIF image format.
+ case GIF
+
+ struct HeaderData {
+ static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
+ static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
+ static var JPEG_IF: [UInt8] = [0xFF]
+ static var GIF: [UInt8] = [0x47, 0x49, 0x46]
+ }
+
+ /// https://en.wikipedia.org/wiki/JPEG
+ public enum JPEGMarker {
+ case SOF0 //baseline
+ case SOF2 //progressive
+ case DHT //Huffman Table
+ case DQT //Quantization Table
+ case DRI //Restart Interval
+ case SOS //Start Of Scan
+ case RSTn(UInt8) //Restart
+ case APPn //Application-specific
+ case COM //Comment
+ case EOI //End Of Image
+
+ var bytes: [UInt8] {
+ switch self {
+ case .SOF0: return [0xFF, 0xC0]
+ case .SOF2: return [0xFF, 0xC2]
+ case .DHT: return [0xFF, 0xC4]
+ case .DQT: return [0xFF, 0xDB]
+ case .DRI: return [0xFF, 0xDD]
+ case .SOS: return [0xFF, 0xDA]
+ case .RSTn(let n): return [0xFF, 0xD0 + n]
+ case .APPn: return [0xFF, 0xE0]
+ case .COM: return [0xFF, 0xFE]
+ case .EOI: return [0xFF, 0xD9]
+ }
+ }
+ }
+}
+
+
+extension Data: KingfisherCompatibleValue {}
+
+// MARK: - Misc Helpers
+extension KingfisherWrapper where Base == Data {
+ /// Gets the image format corresponding to the data.
+ public var imageFormat: ImageFormat {
+ guard base.count > 8 else { return .unknown }
+
+ var buffer = [UInt8](repeating: 0, count: 8)
+ base.copyBytes(to: &buffer, count: 8)
+
+ if buffer == ImageFormat.HeaderData.PNG {
+ return .PNG
+
+ } else if buffer[0] == ImageFormat.HeaderData.JPEG_SOI[0],
+ buffer[1] == ImageFormat.HeaderData.JPEG_SOI[1],
+ buffer[2] == ImageFormat.HeaderData.JPEG_IF[0]
+ {
+ return .JPEG
+
+ } else if buffer[0] == ImageFormat.HeaderData.GIF[0],
+ buffer[1] == ImageFormat.HeaderData.GIF[1],
+ buffer[2] == ImageFormat.HeaderData.GIF[2]
+ {
+ return .GIF
+ }
+
+ return .unknown
+ }
+
+ public func contains(jpeg marker: ImageFormat.JPEGMarker) -> Bool {
+ guard imageFormat == .JPEG else {
+ return false
+ }
+
+ var buffer = [UInt8](repeating: 0, count: base.count)
+ base.copyBytes(to: &buffer, count: base.count)
+ for (index, item) in buffer.enumerated() {
+ guard
+ item == marker.bytes.first,
+ buffer.count > index + 1,
+ buffer[index + 1] == marker.bytes[1] else {
+ continue
+ }
+ return true
+ }
+ return false
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Image/ImageProcessor.swift b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift
new file mode 100644
index 0000000..d21d137
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift
@@ -0,0 +1,837 @@
+//
+// ImageProcessor.swift
+// Kingfisher
+//
+// Created by Wei Wang on 2016/08/26.
+//
+// Copyright (c) 2019 Wei Wang
+//
+// 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
+
+#if canImport(AppKit)
+import AppKit
+#endif
+
+/// Represents an item which could be processed by an `ImageProcessor`.
+///
+/// - image: Input image. The processor should provide a way to apply
+/// processing on this `image` and return the result image.
+/// - data: Input data. The processor should provide a way to apply
+/// processing on this `image` and return the result image.
+public enum ImageProcessItem {
+
+ /// Input image. The processor should provide a way to apply
+ /// processing on this `image` and return the result image.
+ case image(Image)
+
+ /// Input data. The processor should provide a way to apply
+ /// processing on this `image` and return the result image.
+ case data(Data)
+}
+
+/// An `ImageProcessor` would be used to convert some downloaded data to an image.
+public protocol ImageProcessor {
+ /// Identifier of the processor. It will be used to identify the processor when
+ /// caching and retrieving an image. You might want to make sure that processors with
+ /// same properties/functionality have the same identifiers, so correct processed images
+ /// could be retrieved with proper key.
+ ///
+ /// - Note: Do not supply an empty string for a customized processor, which is already reserved by
+ /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of
+ /// your own for the identifier.
+ var identifier: String { get }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: The return value should be `nil` if processing failed while converting an input item to image.
+ /// If `nil` received by the processing caller, an error will be reported and the process flow stops.
+ /// If the processing flow is not critical for your flow, then when the input item is already an image
+ /// (`.image` case) and there is any errors in the processing, you could return the input image itself
+ /// to keep the processing pipeline continuing.
+ /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
+ /// a filter, the input image will be returned directly on watchOS.
+ /// - Note:
+ /// This method is deprecated. Please implement the version with
+ /// `KingfisherParsedOptionsInfo` as parameter instead.
+ @available(*, deprecated,
+ message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.")
+ func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: The parsed options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: The return value should be `nil` if processing failed while converting an input item to image.
+ /// If `nil` received by the processing caller, an error will be reported and the process flow stops.
+ /// If the processing flow is not critical for your flow, then when the input item is already an image
+ /// (`.image` case) and there is any errors in the processing, you could return the input image itself
+ /// to keep the processing pipeline continuing.
+ /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
+ /// a filter, the input image will be returned directly on watchOS.
+ func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image?
+}
+
+extension ImageProcessor {
+ public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
+ return process(item: item, options: KingfisherParsedOptionsInfo(options))
+ }
+}
+
+extension ImageProcessor {
+
+ /// Appends 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
+ }
+ }
+ }
+}
+
+func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
+ return left.identifier == right.identifier
+}
+
+func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
+ return !(left == right)
+}
+
+typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> Image?)
+struct GeneralProcessor: ImageProcessor {
+ let identifier: String
+ let p: ProcessorImp
+ func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ return p(item, options)
+ }
+}
+
+/// The default processor. It converts the input data to a valid image.
+/// Images of .PNG, .JPEG and .GIF format are supported.
+/// If an image item is given as `.image` case, `DefaultImageProcessor` will
+/// do nothing on it and return the associated image.
+public struct DefaultImageProcessor: ImageProcessor {
+
+ /// A default `DefaultImageProcessor` could be used across.
+ public static let `default` = DefaultImageProcessor()
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier = ""
+
+ /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance,
+ /// if you do not have a good reason to create your own `DefaultImageProcessor`.
+ public init() {}
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ case .data(let data):
+ return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
+ }
+ }
+}
+
+/// Represents the rect corner setting when processing a round corner image.
+public struct RectCorner: OptionSet {
+
+ /// Raw value of the rect corner.
+ public let rawValue: Int
+
+ /// Represents the top left corner.
+ public static let topLeft = RectCorner(rawValue: 1 << 0)
+
+ /// Represents the top right corner.
+ public static let topRight = RectCorner(rawValue: 1 << 1)
+
+ /// Represents the bottom left corner.
+ public static let bottomLeft = RectCorner(rawValue: 1 << 2)
+
+ /// Represents the bottom right corner.
+ public static let bottomRight = RectCorner(rawValue: 1 << 3)
+
+ /// Represents all corners.
+ public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
+
+ /// Creates a `RectCorner` option set with a given value.
+ ///
+ /// - Parameter rawValue: The value represents a certain corner option.
+ public init(rawValue: Int) {
+ self.rawValue = rawValue
+ }
+
+ var cornerIdentifier: String {
+ if self == .all {
+ return ""
+ }
+ return "_corner(\(rawValue))"
+ }
+}
+
+#if !os(macOS)
+/// Processor for adding an blend mode to images. Only CG-based images are supported.
+public struct BlendImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Blend Mode will be used to blend the input image.
+ public let blendMode: CGBlendMode
+
+ /// Alpha will be used when blend image.
+ public let alpha: CGFloat
+
+ /// Background color of the output image. If `nil`, it will stay transparent.
+ public let backgroundColor: Color?
+
+ /// Creates a `BlendImageProcessor`.
+ ///
+ /// - Parameters:
+ /// - blendMode: Blend Mode will be used to blend the input image.
+ /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image,
+ /// 0.0 means transparent image (not visible at all). Default is 1.0.
+ /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
+ public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) {
+ self.blendMode = blendMode
+ self.alpha = alpha
+ self.backgroundColor = backgroundColor
+ var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
+ if let color = backgroundColor {
+ identifier.append("_\(color.hex)")
+ }
+ self.identifier = identifier
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+#endif
+
+#if os(macOS)
+/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
+public struct CompositingImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Compositing operation will be used to the input image.
+ public let compositingOperation: NSCompositingOperation
+
+ /// Alpha will be used when compositing image.
+ public let alpha: CGFloat
+
+ /// Background color of the output image. If `nil`, it will stay transparent.
+ public let backgroundColor: Color?
+
+ /// Creates a `CompositingImageProcessor`
+ ///
+ /// - Parameters:
+ /// - compositingOperation: Compositing operation will be used to the input image.
+ /// - alpha: Alpha will be used when compositing image.
+ /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
+ /// Default is 1.0.
+ /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
+ public init(compositingOperation: NSCompositingOperation,
+ alpha: CGFloat = 1.0,
+ backgroundColor: Color? = nil)
+ {
+ self.compositingOperation = compositingOperation
+ self.alpha = alpha
+ self.backgroundColor = backgroundColor
+ var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
+ if let color = backgroundColor {
+ identifier.append("_\(color.hex)")
+ }
+ self.identifier = identifier
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.image(
+ withCompositingOperation: compositingOperation,
+ alpha: alpha,
+ backgroundColor: backgroundColor)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+#endif
+
+/// Processor for making round corner images. Only CG-based images are supported in macOS,
+/// if a non-CG image passed in, the processor will do nothing.
+///
+/// Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain
+/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order
+/// to show correctly. However, when cached into disk, the image format will be respected and the alpha channel will
+/// be removed. That means when you load the processed image from cache again, you will lose transparent corner.
+/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this
+/// case.
+public struct RoundCornerImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Corner radius will be applied in processing.
+ public let cornerRadius: CGFloat
+
+ /// The target corners which will be applied rounding.
+ public let roundingCorners: RectCorner
+
+ /// Target size of output image should be. If `nil`, the image will keep its original size after processing.
+ public let targetSize: CGSize?
+
+ /// Background color of the output image. If `nil`, it will use a transparent background.
+ public let backgroundColor: Color?
+
+ /// Creates a `RoundCornerImageProcessor`.
+ ///
+ /// - Parameters:
+ /// - cornerRadius: Corner radius will be applied in processing.
+ /// - targetSize: Target size of output image should be. If `nil`,
+ /// the image will keep its original size after processing.
+ /// Default is `nil`.
+ /// - corners: The target corners which will be applied rounding. Default is `.all`.
+ /// - backgroundColor: Background color to apply for the output image. Default is `nil`.
+ public init(
+ cornerRadius: CGFloat,
+ targetSize: CGSize? = nil,
+ roundingCorners corners: RectCorner = .all,
+ backgroundColor: Color? = nil)
+ {
+ self.cornerRadius = cornerRadius
+ self.targetSize = targetSize
+ self.roundingCorners = corners
+ self.backgroundColor = backgroundColor
+
+ self.identifier = {
+ var identifier = ""
+
+ if let size = targetSize {
+ identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
+ "(\(cornerRadius)_\(size)\(corners.cornerIdentifier))"
+ } else {
+ identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
+ "(\(cornerRadius)\(corners.cornerIdentifier))"
+ }
+ if let backgroundColor = backgroundColor {
+ identifier += "_\(backgroundColor)"
+ }
+
+ return identifier
+ }()
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ let size = targetSize ?? image.kf.size
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.image(
+ withRoundRadius: cornerRadius,
+ fit: size,
+ roundingCorners: roundingCorners,
+ backgroundColor: backgroundColor)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+
+/// Represents how a size adjusts itself to fit a target size.
+///
+/// - none: Not scale the content.
+/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio.
+/// - aspectFill: Scales the content to fill the size of the view.
+public enum ContentMode {
+ /// Not scale the content.
+ case none
+ /// Scales the content to fit the size of the view by maintaining the aspect ratio.
+ case aspectFit
+ /// Scales the content to fill the size of the view.
+ case aspectFill
+}
+
+/// Processor for resizing images.
+/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
+/// instead, which is more efficient and takes less memory.
+public struct ResizingImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// The reference size for resizing operation in point.
+ public let referenceSize: CGSize
+
+ /// Target content mode of output image should be.
+ /// Default is `.none`.
+ public let targetContentMode: ContentMode
+
+ /// Creates a `ResizingImageProcessor`.
+ ///
+ /// - Parameters:
+ /// - referenceSize: The reference size for resizing operation in point.
+ /// - mode: Target content mode of output image should be.
+ ///
+ /// - Note:
+ /// The instance of `ResizingImageProcessor` will follow its `mode` property
+ /// and try to resizing the input images to fit or fill the `referenceSize`.
+ /// That means if you are using a `mode` besides of `.none`, you may get an
+ /// image with its size not be the same as the `referenceSize`.
+ ///
+ /// **Example**: With input image size: {100, 200},
+ /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
+ /// you will get an output image with size of {50, 100}, which "fit"s
+ /// the `referenceSize`.
+ ///
+ /// If you need an output image exactly to be a specified size, append or use
+ /// a `CroppingImageProcessor`.
+ public init(referenceSize: CGSize, mode: ContentMode = .none) {
+ self.referenceSize = referenceSize
+ self.targetContentMode = mode
+
+ if mode == .none {
+ self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
+ } else {
+ self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
+ }
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.resize(to: referenceSize, for: targetContentMode)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
+/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
+public struct BlurImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Blur radius for the simulated Gaussian blur.
+ public let blurRadius: CGFloat
+
+ /// Creates a `BlurImageProcessor`
+ ///
+ /// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
+ public init(blurRadius: CGFloat) {
+ self.blurRadius = blurRadius
+ self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ let radius = blurRadius * options.scaleFactor
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.blurred(withRadius: radius)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
+public struct OverlayImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Overlay color will be used to overlay the input image.
+ public let overlay: Color
+
+ /// Fraction will be used when overlay the color to image.
+ public let fraction: CGFloat
+
+ /// Creates an `OverlayImageProcessor`
+ ///
+ /// - parameter overlay: Overlay color will be used to overlay the input image.
+ /// - parameter fraction: Fraction will be used when overlay the color to image.
+ /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
+ public init(overlay: Color, fraction: CGFloat = 0.5) {
+ self.overlay = overlay
+ self.fraction = fraction
+ self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.overlaying(with: overlay, fraction: fraction)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for tint images with color. Only CG-based images are supported.
+public struct TintImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Tint color will be used to tint the input image.
+ public let tint: Color
+
+ /// Creates a `TintImageProcessor`
+ ///
+ /// - parameter tint: Tint color will be used to tint the input image.
+ public init(tint: Color) {
+ self.tint = tint
+ self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.tinted(with: tint)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for applying some color control to images. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct ColorControlsProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Brightness changing to image.
+ public let brightness: CGFloat
+
+ /// Contrast changing to image.
+ public let contrast: CGFloat
+
+ /// Saturation changing to image.
+ public let saturation: CGFloat
+
+ /// InputEV changing to image.
+ public let inputEV: CGFloat
+
+ /// Creates a `ColorControlsProcessor`
+ ///
+ /// - Parameters:
+ /// - brightness: Brightness changing to image.
+ /// - contrast: Contrast changing to image.
+ /// - saturation: Saturation changing to image.
+ /// - inputEV: InputEV changing to image.
+ public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.inputEV = inputEV
+ self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
+ case .data:
+ return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for applying black and white effect to images. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct BlackWhiteProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
+
+ /// Creates a `BlackWhiteProcessor`
+ public init() {}
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
+ .process(item: item, options: options)
+ }
+}
+
+/// Processor for cropping an image. Only CG-based images are supported.
+/// watchOS is not supported.
+public struct CroppingImageProcessor: ImageProcessor {
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Target size of output image should be.
+ public let size: CGSize
+
+ /// Anchor point from which the output size should be calculate.
+ /// The anchor point is consisted by two values between 0.0 and 1.0.
+ /// It indicates a related point in current image.
+ /// See `CroppingImageProcessor.init(size:anchor:)` for more.
+ public let anchor: CGPoint
+
+ /// Creates a `CroppingImageProcessor`.
+ ///
+ /// - Parameters:
+ /// - size: Target size of output image should be.
+ /// - anchor: The anchor point from which the size should be calculated.
+ /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
+ /// - Note:
+ /// The anchor point is consisted by two values between 0.0 and 1.0.
+ /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
+ /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
+ /// The `size` property of `CroppingImageProcessor` will be used along with
+ /// `anchor` to calculate a target rectangle in the size of image.
+ ///
+ /// The target size will be automatically calculated with a reasonable behavior.
+ /// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
+ /// and a target size of `CGSize(width: 20, height: 20)`:
+ /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
+ /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
+ /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
+ public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
+ self.size = size
+ self.anchor = anchor
+ self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ return image.kf.scaled(to: options.scaleFactor)
+ .kf.crop(to: size, anchorOn: anchor)
+ case .data: return (DefaultImageProcessor.default >> self).process(item: item, options: options)
+ }
+ }
+}
+
+/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor
+/// does not render the images to resize. Instead, it downsample the input data directly to an
+/// image. It is a more efficient than `ResizingImageProcessor`.
+///
+/// Only CG-based images are supported. Animated images (like GIF) is not supported.
+public struct DownsamplingImageProcessor: ImageProcessor {
+
+ /// Target size of output image should be. It should be smaller than the size of
+ /// input image. If it is larger, the result image will be the same size of input
+ /// data without downsampling.
+ public let size: CGSize
+
+ /// Identifier of the processor.
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public let identifier: String
+
+ /// Creates a `DownsamplingImageProcessor`.
+ ///
+ /// - Parameter size: The target size of the downsample operation.
+ public init(size: CGSize) {
+ self.size = size
+ self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))"
+ }
+
+ /// Processes the input `ImageProcessItem` with this processor.
+ ///
+ /// - Parameters:
+ /// - item: Input item which will be processed by `self`.
+ /// - options: Options when processing the item.
+ /// - Returns: The processed image.
+ ///
+ /// - Note: See documentation of `ImageProcessor` protocol for more.
+ public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
+ switch item {
+ case .image(let image):
+ guard let data = image.kf.data(format: .unknown) else {
+ return nil
+ }
+ return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
+ case .data(let data):
+ return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
+ }
+ }
+}
+
+/// Concatenates two `ImageProcessor`s. `ImageProcessor.append(another:)` is used internally.
+///
+/// - Parameters:
+/// - left: The first processor.
+/// - right: The second processor.
+/// - Returns: The concatenated processor.
+public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
+ return left.append(another: right)
+}
+
+extension Color {
+ var hex: String {
+ var r: CGFloat = 0
+ var g: CGFloat = 0
+ var b: CGFloat = 0
+ var a: CGFloat = 0
+
+ #if os(macOS)
+ (usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
+ #else
+ getRed(&r, green: &g, blue: &b, alpha: &a)
+ #endif
+
+ let rInt = Int(r * 255) << 24
+ let gInt = Int(g * 255) << 16
+ let bInt = Int(b * 255) << 8
+ let aInt = Int(a * 255)
+
+ let rgba = rInt | gInt | bInt | aInt
+
+ return String(format:"#%08x", rgba)
+ }
+}
diff --git a/Pods/Kingfisher/Sources/Image/ImageProgressive.swift b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift
new file mode 100644
index 0000000..2331a50
--- /dev/null
+++ b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift
@@ -0,0 +1,309 @@
+//
+// ImageProgressive.swift
+// Kingfisher
+//
+// Created by lixiang on 2019/5/10.
+//
+// Copyright (c) 2019 Wei Wang