2
0

ImageDataProvider.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //
  2. // ImageDataProvider.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/11/13.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// Represents a data provider to provide image data to Kingfisher when setting with
  28. /// ``Source/provider(_:)`` source. Compared to ``Source/network(_:)`` member, it gives a chance
  29. /// to load some image data in your own way, as long as you can provide the data
  30. /// representation for the image.
  31. public protocol ImageDataProvider: Sendable {
  32. /// The key used in cache.
  33. var cacheKey: String { get }
  34. /// Provides the data which represents image. Kingfisher uses the data you pass in the
  35. /// handler to process images and caches it for later use.
  36. ///
  37. /// - Parameter handler: The handler you should call when you prepared your data.
  38. /// If the data is loaded successfully, call the handler with
  39. /// a `.success` with the data associated. Otherwise, call it
  40. /// with a `.failure` and pass the error.
  41. ///
  42. /// - Note: If the `handler` is called with a `.failure` with error,
  43. /// a ``KingfisherError/ImageSettingErrorReason/dataProviderError(provider:error:)`` will be finally thrown out to
  44. /// you as the ``KingfisherError`` from the framework.
  45. func data(handler: @escaping @Sendable (Result<Data, any Error>) -> Void)
  46. /// The content URL represents this provider, if exists.
  47. var contentURL: URL? { get }
  48. }
  49. extension ImageDataProvider {
  50. func data() async throws -> Data {
  51. try await withCheckedThrowingContinuation { continuation in
  52. data(handler: { continuation.resume(with: $0) })
  53. }
  54. }
  55. }
  56. public extension ImageDataProvider {
  57. var contentURL: URL? { return nil }
  58. func convertToSource() -> Source {
  59. .provider(self)
  60. }
  61. }
  62. /// Represents an image data provider for loading from a local file URL on disk.
  63. /// Uses this type for adding a disk image to Kingfisher. Compared to loading it
  64. /// directly, you can get benefit of using Kingfisher's extension methods, as well
  65. /// as applying ``ImageProcessor``s and storing the image to ``ImageCache`` of Kingfisher.
  66. public struct LocalFileImageDataProvider: ImageDataProvider {
  67. // MARK: Public Properties
  68. /// The file URL from which the image be loaded.
  69. public let fileURL: URL
  70. private let loadingQueue: ExecutionQueue
  71. // MARK: Initializers
  72. /// Creates an image data provider by supplying the target local file URL.
  73. ///
  74. /// - Parameters:
  75. /// - fileURL: The file URL from which the image be loaded.
  76. /// - cacheKey: The key is used for caching the image data. By default,
  77. /// the `absoluteString` of ``LocalFileImageDataProvider/fileURL`` is used.
  78. /// - loadingQueue: The queue where the file loading should happen. By default, the dispatch queue of
  79. /// `.global(qos: .userInitiated)` will be used.
  80. public init(
  81. fileURL: URL,
  82. cacheKey: String? = nil,
  83. loadingQueue: ExecutionQueue = .dispatch(DispatchQueue.global(qos: .userInitiated))
  84. ) {
  85. self.fileURL = fileURL
  86. self.cacheKey = cacheKey ?? fileURL.localFileCacheKey
  87. self.loadingQueue = loadingQueue
  88. }
  89. // MARK: Protocol Conforming
  90. /// The key used in cache.
  91. public var cacheKey: String
  92. public func data(handler: @escaping @Sendable (Result<Data, any Error>) -> Void) {
  93. loadingQueue.execute {
  94. handler(Result(catching: { try Data(contentsOf: fileURL) }))
  95. }
  96. }
  97. public var data: Data {
  98. get async throws {
  99. try await withCheckedThrowingContinuation { continuation in
  100. loadingQueue.execute {
  101. do {
  102. let data = try Data(contentsOf: fileURL)
  103. continuation.resume(returning: data)
  104. } catch {
  105. continuation.resume(throwing: error)
  106. }
  107. }
  108. }
  109. }
  110. }
  111. /// The URL of the local file on the disk.
  112. public var contentURL: URL? {
  113. return fileURL
  114. }
  115. }
  116. /// Represents an image data provider for loading image from a given Base64 encoded string.
  117. public struct Base64ImageDataProvider: ImageDataProvider {
  118. // MARK: Public Properties
  119. /// The encoded Base64 string for the image.
  120. public let base64String: String
  121. // MARK: Initializers
  122. /// Creates an image data provider by supplying the Base64 encoded string.
  123. ///
  124. /// - Parameters:
  125. /// - base64String: The Base64 encoded string for an image.
  126. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
  127. public init(base64String: String, cacheKey: String) {
  128. self.base64String = base64String
  129. self.cacheKey = cacheKey
  130. }
  131. // MARK: Protocol Conforming
  132. /// The key used in cache.
  133. public var cacheKey: String
  134. public func data(handler: (Result<Data, any Error>) -> Void) {
  135. let data = Data(base64Encoded: base64String)!
  136. handler(.success(data))
  137. }
  138. }
  139. /// Represents an image data provider for a raw data object.
  140. public struct RawImageDataProvider: ImageDataProvider {
  141. // MARK: Public Properties
  142. /// The raw data object to provide to Kingfisher image loader.
  143. public let data: Data
  144. // MARK: Initializers
  145. /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache.
  146. ///
  147. /// - Parameters:
  148. /// - data: The raw data represents an image.
  149. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image.
  150. public init(data: Data, cacheKey: String) {
  151. self.data = data
  152. self.cacheKey = cacheKey
  153. }
  154. // MARK: Protocol Conforming
  155. /// The key used in cache.
  156. public var cacheKey: String
  157. public func data(handler: @escaping (Result<Data, any Error>) -> Void) {
  158. handler(.success(data))
  159. }
  160. }