Disk+Data.swift 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import Foundation
  2. public extension Disk {
  3. /// Save Data to disk
  4. ///
  5. /// - Parameters:
  6. /// - value: Data to store to disk
  7. /// - directory: user directory to store the file in
  8. /// - path: file location to store the data (i.e. "Folder/file.mp4")
  9. /// - Throws: Error if there were any issues writing the given data to disk
  10. static func save(_ value: Data, to directory: Directory, as path: String) throws {
  11. do {
  12. let url = try createURL(for: path, in: directory)
  13. try createSubfoldersBeforeCreatingFile(at: url)
  14. try value.write(to: url, options: .atomic)
  15. } catch {
  16. throw error
  17. }
  18. }
  19. /// Retrieve data from disk
  20. ///
  21. /// - Parameters:
  22. /// - path: path where data file is stored
  23. /// - directory: user directory to retrieve the file from
  24. /// - type: here for Swifty generics magic, use Data.self
  25. /// - Returns: Data retrieved from disk
  26. /// - Throws: Error if there were any issues retrieving the specified file's data
  27. static func retrieve(_ path: String, from directory: Directory, as _: Data.Type) throws -> Data {
  28. do {
  29. let url = try getExistingFileURL(for: path, in: directory)
  30. let data = try Data(contentsOf: url)
  31. return data
  32. } catch {
  33. throw error
  34. }
  35. }
  36. }