Disk+VolumeInformation.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import Foundation
  2. /// Checking Volume Storage Capacity
  3. /// Confirm that you have enough local storage space for a large amount of data.
  4. ///
  5. /// Source: https://developer.apple.com/documentation/foundation/nsurlresourcekey/checking_volume_storage_capacity?changes=latest_major&language=objc
  6. @available(iOS 11.0, *)
  7. public extension Disk {
  8. /// Helper method to query against a resource value key
  9. private static func getVolumeResourceValues(for key: URLResourceKey) -> URLResourceValues? {
  10. let fileUrl = URL(fileURLWithPath: "/")
  11. let results = try? fileUrl.resourceValues(forKeys: [key])
  12. return results
  13. }
  14. /// Volume’s total capacity in bytes.
  15. static var totalCapacity: Int? {
  16. let resourceValues = getVolumeResourceValues(for: .volumeTotalCapacityKey)
  17. return resourceValues?.volumeTotalCapacity
  18. }
  19. /// Volume’s available capacity in bytes.
  20. static var availableCapacity: Int? {
  21. let resourceValues = getVolumeResourceValues(for: .volumeAvailableCapacityKey)
  22. return resourceValues?.volumeAvailableCapacity
  23. }
  24. /// Volume’s available capacity in bytes for storing important resources.
  25. ///
  26. /// Indicates the amount of space that can be made available for things the user has explicitly requested in the app's UI (i.e. downloading a video or new level for a game.)
  27. /// If you need more space than what's available - let user know the request cannot be fulfilled.
  28. static var availableCapacityForImportantUsage: Int? {
  29. let resourceValues = getVolumeResourceValues(for: .volumeAvailableCapacityForImportantUsageKey)
  30. if let result = resourceValues?.volumeAvailableCapacityForImportantUsage {
  31. return Int(exactly: result)
  32. } else {
  33. return nil
  34. }
  35. }
  36. /// Volume’s available capacity in bytes for storing nonessential resources.
  37. ///
  38. /// Indicates the amount of space available for things that the user is likely to want but hasn't explicitly requested (i.e. next episode in video series they're watching, or recently updated documents in a server that they might be likely to open.)
  39. /// For these types of files you might store them initially in the caches directory until they are actually used, at which point you can move them in app support or documents directory.
  40. static var availableCapacityForOpportunisticUsage: Int? {
  41. let resourceValues = getVolumeResourceValues(for: .volumeAvailableCapacityForOpportunisticUsageKey)
  42. if let result = resourceValues?.volumeAvailableCapacityForOpportunisticUsage {
  43. return Int(exactly: result)
  44. } else {
  45. return nil
  46. }
  47. }
  48. }