DiskStorage.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. //
  2. // DiskStorage.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/15.
  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 the concepts related to storage that stores a specific type of value in disk.
  28. ///
  29. /// This serves as a namespace for memory storage types. A ``DiskStorage/Backend`` with a particular
  30. /// ``DiskStorage/Config`` is used to define the storage.
  31. ///
  32. /// Refer to these composite types for further details.
  33. public enum DiskStorage {
  34. /// Represents a storage backend for the ``DiskStorage``.
  35. ///
  36. /// The value is serialized to binary data and stored as a file in the file system under a specified location.
  37. ///
  38. /// You can configure a ``DiskStorage/Backend`` in its ``DiskStorage/Backend/init(config:)`` by passing a
  39. /// ``DiskStorage/Config`` value or by modifying the ``DiskStorage/Backend/config`` property after it has been
  40. /// created. The ``DiskStorage/Backend`` will use the file's attributes to keep track of a file for its expiration
  41. /// or size limitation.
  42. public class Backend<T: DataTransformable> {
  43. /// The configuration used for this disk storage.
  44. ///
  45. /// It is a value you can set and use to configure the storage as needed.
  46. public var config: Config
  47. /// The final storage URL on disk of the disk storage ``DiskStorage/Backend``, considering the
  48. /// ``DiskStorage/Config/name`` and the ``DiskStorage/Config/cachePathBlock``.
  49. public let directoryURL: URL
  50. let metaChangingQueue: DispatchQueue
  51. // A shortcut (which contains false-positive) to improve matching performance.
  52. var maybeCached : Set<String>?
  53. let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
  54. // `false` if the storage initialized with an error.
  55. // This prevents unexpected forcibly crash when creating storage in the default cache.
  56. private var storageReady: Bool = true
  57. /// Creates a disk storage with the given ``DiskStorage/Config``.
  58. ///
  59. /// - Parameter config: The configuration used for this disk storage.
  60. /// - Throws: An error if the folder for storage cannot be obtained or created.
  61. public convenience init(config: Config) throws {
  62. self.init(noThrowConfig: config, creatingDirectory: false)
  63. try prepareDirectory()
  64. }
  65. // If `creatingDirectory` is `false`, the directory preparation will be skipped.
  66. // We need to call `prepareDirectory` manually after this returns.
  67. init(noThrowConfig config: Config, creatingDirectory: Bool) {
  68. var config = config
  69. let creation = Creation(config)
  70. self.directoryURL = creation.directoryURL
  71. // Break any possible retain cycle set by outside.
  72. config.cachePathBlock = nil
  73. self.config = config
  74. metaChangingQueue = DispatchQueue(label: creation.cacheName)
  75. setupCacheChecking()
  76. if creatingDirectory {
  77. try? prepareDirectory()
  78. }
  79. }
  80. private func setupCacheChecking() {
  81. maybeCachedCheckingQueue.async {
  82. do {
  83. self.maybeCached = Set()
  84. try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach {
  85. fileName in
  86. self.maybeCached?.insert(fileName)
  87. }
  88. } catch {
  89. // Just disable the functionality if we fail to initialize it properly. This will just revert to
  90. // the behavior which is to check file existence on disk directly.
  91. self.maybeCached = nil
  92. }
  93. }
  94. }
  95. // Creates the storage folder.
  96. private func prepareDirectory() throws {
  97. let fileManager = config.fileManager
  98. let path = directoryURL.path
  99. guard !fileManager.fileExists(atPath: path) else { return }
  100. do {
  101. try fileManager.createDirectory(
  102. atPath: path,
  103. withIntermediateDirectories: true,
  104. attributes: nil)
  105. } catch {
  106. self.storageReady = false
  107. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  108. }
  109. }
  110. /// Stores a value in the storage under the specified key and expiration policy.
  111. ///
  112. /// - Parameters:
  113. /// - value: The value to be stored.
  114. /// - key: The key to which the `value` will be stored. If there is already a value under the key,
  115. /// the old value will be overwritten by the new `value`.
  116. /// - expiration: The expiration policy used by this storage action.
  117. /// - writeOptions: Data writing options used for the new files.
  118. /// - Throws: An error during converting the value to a data format or during writing it to disk.
  119. public func store(
  120. value: T,
  121. forKey key: String,
  122. expiration: StorageExpiration? = nil,
  123. writeOptions: Data.WritingOptions = []) throws
  124. {
  125. guard storageReady else {
  126. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  127. }
  128. let expiration = expiration ?? config.expiration
  129. // The expiration indicates that already expired, no need to store.
  130. guard !expiration.isExpired else { return }
  131. let data: Data
  132. do {
  133. data = try value.toData()
  134. } catch {
  135. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  136. }
  137. let fileURL = cacheFileURL(forKey: key)
  138. do {
  139. try data.write(to: fileURL, options: writeOptions)
  140. } catch {
  141. if error.isFolderMissing {
  142. // The whole cache folder is deleted. Try to recreate it and write file again.
  143. do {
  144. try prepareDirectory()
  145. try data.write(to: fileURL, options: writeOptions)
  146. } catch {
  147. throw KingfisherError.cacheError(
  148. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  149. )
  150. }
  151. } else {
  152. throw KingfisherError.cacheError(
  153. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  154. )
  155. }
  156. }
  157. let now = Date()
  158. let attributes: [FileAttributeKey : Any] = [
  159. // The last access date.
  160. .creationDate: now.fileAttributeDate,
  161. // The estimated expiration date.
  162. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  163. ]
  164. do {
  165. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  166. } catch {
  167. try? config.fileManager.removeItem(at: fileURL)
  168. throw KingfisherError.cacheError(
  169. reason: .cannotSetCacheFileAttribute(
  170. filePath: fileURL.path,
  171. attributes: attributes,
  172. error: error
  173. )
  174. )
  175. }
  176. maybeCachedCheckingQueue.async {
  177. self.maybeCached?.insert(fileURL.lastPathComponent)
  178. }
  179. }
  180. /// Retrieves a value from the storage.
  181. /// - Parameters:
  182. /// - key: The cache key of the value.
  183. /// - extendingExpiration: The expiration policy used by this retrieval action.
  184. /// - Throws: An error during converting the data to a value or during the operation of disk files.
  185. /// - Returns: The value under `key` if it is valid and found in the storage; otherwise, `nil`.
  186. public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  187. try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  188. }
  189. func value(
  190. forKey key: String,
  191. referenceDate: Date,
  192. actuallyLoad: Bool,
  193. extendingExpiration: ExpirationExtending) throws -> T?
  194. {
  195. guard storageReady else {
  196. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  197. }
  198. let fileManager = config.fileManager
  199. let fileURL = cacheFileURL(forKey: key)
  200. let filePath = fileURL.path
  201. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  202. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  203. }
  204. guard fileMaybeCached else {
  205. return nil
  206. }
  207. guard fileManager.fileExists(atPath: filePath) else {
  208. return nil
  209. }
  210. let meta: FileMeta
  211. do {
  212. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  213. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  214. } catch {
  215. throw KingfisherError.cacheError(
  216. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  217. }
  218. if meta.expired(referenceDate: referenceDate) {
  219. return nil
  220. }
  221. if !actuallyLoad { return T.empty }
  222. do {
  223. let data = try Data(contentsOf: fileURL)
  224. let obj = try T.fromData(data)
  225. metaChangingQueue.async {
  226. meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
  227. }
  228. return obj
  229. } catch {
  230. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  231. }
  232. }
  233. /// Determines whether there is valid cached data under a given key.
  234. ///
  235. /// - Parameter key: The cache key of the value.
  236. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  237. ///
  238. /// > This method does not actually load the data from disk, so it is faster than directly loading the cached
  239. /// value by checking the nullability of the ``DiskStorage/Backend/value(forKey:extendingExpiration:)`` method.
  240. public func isCached(forKey key: String) -> Bool {
  241. return isCached(forKey: key, referenceDate: Date())
  242. }
  243. /// Determines whether there is valid cached data under a given key and a reference date.
  244. ///
  245. /// - Parameters:
  246. /// - key: The cache key of the value.
  247. /// - referenceDate: A reference date to check whether the cache is still valid.
  248. ///
  249. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  250. ///
  251. /// If you pass `Date()` as the `referenceDate`, this method is identical to
  252. /// ``DiskStorage/Backend/isCached(forKey:)``. Use the `referenceDate` to determine whether the cache is still
  253. /// valid for a future date.
  254. public func isCached(forKey key: String, referenceDate: Date) -> Bool {
  255. do {
  256. let result = try value(
  257. forKey: key,
  258. referenceDate: referenceDate,
  259. actuallyLoad: false,
  260. extendingExpiration: .none
  261. )
  262. return result != nil
  263. } catch {
  264. return false
  265. }
  266. }
  267. /// Removes a value from a specified key.
  268. /// - Parameter key: The cache key of the value.
  269. /// - Throws: An error during the removal of the value.
  270. public func remove(forKey key: String) throws {
  271. let fileURL = cacheFileURL(forKey: key)
  272. try removeFile(at: fileURL)
  273. }
  274. func removeFile(at url: URL) throws {
  275. try config.fileManager.removeItem(at: url)
  276. }
  277. /// Removes all values in this storage.
  278. /// - Throws: An error during the removal of the values.
  279. public func removeAll() throws {
  280. try removeAll(skipCreatingDirectory: false)
  281. }
  282. func removeAll(skipCreatingDirectory: Bool) throws {
  283. try config.fileManager.removeItem(at: directoryURL)
  284. if !skipCreatingDirectory {
  285. try prepareDirectory()
  286. }
  287. }
  288. /// The URL of the cached file with a given computed `key`.
  289. ///
  290. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  291. /// the ``Source/cacheKey`` of an image ``Source``. It is the computed key with the processor identifier
  292. /// considered.
  293. ///
  294. /// This method does not guarantee that an image is already cached at the returned URL. It just provides the URL
  295. /// where the image should be if it exists in the disk storage, with the given key.
  296. public func cacheFileURL(forKey key: String) -> URL {
  297. let fileName = cacheFileName(forKey: key)
  298. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  299. }
  300. func cacheFileName(forKey key: String) -> String {
  301. if config.usesHashedFileName {
  302. let hashedKey = key.kf.sha256
  303. if let ext = config.pathExtension {
  304. return "\(hashedKey).\(ext)"
  305. } else if config.autoExtAfterHashedFileName,
  306. let ext = key.kf.ext {
  307. return "\(hashedKey).\(ext)"
  308. }
  309. return hashedKey
  310. } else {
  311. if let ext = config.pathExtension {
  312. return "\(key).\(ext)"
  313. }
  314. return key
  315. }
  316. }
  317. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  318. let fileManager = config.fileManager
  319. guard let directoryEnumerator = fileManager.enumerator(
  320. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  321. {
  322. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  323. }
  324. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  325. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  326. }
  327. return urls
  328. }
  329. /// Removes all expired values from this storage.
  330. /// - Throws: A file manager error during the removal of the file.
  331. /// - Returns: The URLs for the removed files.
  332. public func removeExpiredValues() throws -> [URL] {
  333. return try removeExpiredValues(referenceDate: Date())
  334. }
  335. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  336. let propertyKeys: [URLResourceKey] = [
  337. .isDirectoryKey,
  338. .contentModificationDateKey
  339. ]
  340. let urls = try allFileURLs(for: propertyKeys)
  341. let keys = Set(propertyKeys)
  342. let expiredFiles = urls.filter { fileURL in
  343. do {
  344. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  345. if meta.isDirectory {
  346. return false
  347. }
  348. return meta.expired(referenceDate: referenceDate)
  349. } catch {
  350. return true
  351. }
  352. }
  353. try expiredFiles.forEach { url in
  354. try removeFile(at: url)
  355. }
  356. return expiredFiles
  357. }
  358. /// Removes all size-exceeded values from this storage.
  359. /// - Throws: A file manager error during the removal of the file.
  360. /// - Returns: The URLs for the removed files.
  361. ///
  362. /// This method checks ``DiskStorage/Config/sizeLimit`` and removes cached files in an LRU
  363. /// (Least Recently Used) way.
  364. func removeSizeExceededValues() throws -> [URL] {
  365. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  366. var size = try totalSize()
  367. if size < config.sizeLimit { return [] }
  368. let propertyKeys: [URLResourceKey] = [
  369. .isDirectoryKey,
  370. .creationDateKey,
  371. .fileSizeKey
  372. ]
  373. let keys = Set(propertyKeys)
  374. let urls = try allFileURLs(for: propertyKeys)
  375. var pendings: [FileMeta] = urls.compactMap { fileURL in
  376. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  377. return nil
  378. }
  379. return meta
  380. }
  381. // Sort by last access date. Most recent file first.
  382. pendings.sort(by: FileMeta.lastAccessDate)
  383. var removed: [URL] = []
  384. let target = config.sizeLimit / 2
  385. while size > target, let meta = pendings.popLast() {
  386. size -= UInt(meta.fileSize)
  387. try removeFile(at: meta.url)
  388. removed.append(meta.url)
  389. }
  390. return removed
  391. }
  392. /// Gets the total file size of the cache folder in bytes.
  393. public func totalSize() throws -> UInt {
  394. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  395. let urls = try allFileURLs(for: propertyKeys)
  396. let keys = Set(propertyKeys)
  397. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  398. do {
  399. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  400. return size + UInt(meta.fileSize)
  401. } catch {
  402. return size
  403. }
  404. }
  405. return totalSize
  406. }
  407. }
  408. }
  409. extension DiskStorage {
  410. /// Represents the configuration used in a ``DiskStorage/Backend``.
  411. public struct Config {
  412. /// The file size limit on disk of the storage in bytes.
  413. ///
  414. /// `0` means no limit.
  415. public var sizeLimit: UInt
  416. /// The `StorageExpiration` used in this disk storage.
  417. ///
  418. /// The default is `.days(7)`, which means that the disk cache will expire in one week if not accessed anymore.
  419. public var expiration: StorageExpiration = .days(7)
  420. /// The preferred extension of the cache item. It will be appended to the file name as its extension.
  421. ///
  422. /// The default is `nil`, which means that the cache file does not contain a file extension.
  423. public var pathExtension: String? = nil
  424. /// Whether the cache file name will be hashed before storing.
  425. ///
  426. /// The default is `true`, which means that file name is hashed to protect user information (for example, the
  427. /// original download URL which is used as the cache key).
  428. public var usesHashedFileName = true
  429. /// Whether the image extension will be extracted from the original file name and appended to the hashed file
  430. /// name, which will be used as the cache key on disk.
  431. ///
  432. /// The default is `false`.
  433. public var autoExtAfterHashedFileName = false
  434. /// A closure that takes in the initial directory path and generates the final disk cache path.
  435. ///
  436. /// You can use it to fully customize your cache path.
  437. public var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  438. (directory, cacheName) in
  439. return directory.appendingPathComponent(cacheName, isDirectory: true)
  440. }
  441. /// The desired name of the disk cache.
  442. ///
  443. /// This name will be used as a part of the cache folder name by default.
  444. public let name: String
  445. let fileManager: FileManager
  446. let directory: URL?
  447. /// Creates a config value based on the given parameters.
  448. ///
  449. /// - Parameters:
  450. /// - name: The name of the cache. It is used as part of the storage folder and to identify the disk storage.
  451. /// Two storages with the same `name` would share the same folder on the disk, and this should be prevented.
  452. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  453. /// - fileManager: The `FileManager` used to manipulate files on the disk. The default is `FileManager.default`.
  454. /// - directory: The URL where the disk storage should reside. The storage will use this as the root folder,
  455. /// and append a path that is constructed by the input `name`. The default is `nil`, indicating that
  456. /// the cache directory under the user domain mask will be used.
  457. public init(
  458. name: String,
  459. sizeLimit: UInt,
  460. fileManager: FileManager = .default,
  461. directory: URL? = nil)
  462. {
  463. self.name = name
  464. self.fileManager = fileManager
  465. self.directory = directory
  466. self.sizeLimit = sizeLimit
  467. }
  468. }
  469. }
  470. extension DiskStorage {
  471. struct FileMeta {
  472. let url: URL
  473. let lastAccessDate: Date?
  474. let estimatedExpirationDate: Date?
  475. let isDirectory: Bool
  476. let fileSize: Int
  477. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  478. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  479. }
  480. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  481. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  482. self.init(
  483. fileURL: fileURL,
  484. lastAccessDate: meta.creationDate,
  485. estimatedExpirationDate: meta.contentModificationDate,
  486. isDirectory: meta.isDirectory ?? false,
  487. fileSize: meta.fileSize ?? 0)
  488. }
  489. init(
  490. fileURL: URL,
  491. lastAccessDate: Date?,
  492. estimatedExpirationDate: Date?,
  493. isDirectory: Bool,
  494. fileSize: Int)
  495. {
  496. self.url = fileURL
  497. self.lastAccessDate = lastAccessDate
  498. self.estimatedExpirationDate = estimatedExpirationDate
  499. self.isDirectory = isDirectory
  500. self.fileSize = fileSize
  501. }
  502. func expired(referenceDate: Date) -> Bool {
  503. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  504. }
  505. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  506. guard let lastAccessDate = lastAccessDate,
  507. let lastEstimatedExpiration = estimatedExpirationDate else
  508. {
  509. return
  510. }
  511. let attributes: [FileAttributeKey : Any]
  512. switch extendingExpiration {
  513. case .none:
  514. // not extending expiration time here
  515. return
  516. case .cacheTime:
  517. let originalExpiration: StorageExpiration =
  518. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  519. attributes = [
  520. .creationDate: Date().fileAttributeDate,
  521. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  522. ]
  523. case .expirationTime(let expirationTime):
  524. attributes = [
  525. .creationDate: Date().fileAttributeDate,
  526. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  527. ]
  528. }
  529. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  530. }
  531. }
  532. }
  533. extension DiskStorage {
  534. struct Creation {
  535. let directoryURL: URL
  536. let cacheName: String
  537. init(_ config: Config) {
  538. let url: URL
  539. if let directory = config.directory {
  540. url = directory
  541. } else {
  542. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  543. }
  544. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  545. directoryURL = config.cachePathBlock(url, cacheName)
  546. }
  547. }
  548. }
  549. fileprivate extension Error {
  550. var isFolderMissing: Bool {
  551. let nsError = self as NSError
  552. guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else {
  553. return false
  554. }
  555. guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else {
  556. return false
  557. }
  558. guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else {
  559. return false
  560. }
  561. return true
  562. }
  563. }