ModelFileManager.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /// Manager for common file operations.
  16. enum ModelFileManager {
  17. /// Root directory of model file storage on device.
  18. static var modelsDirectory: URL {
  19. // TODO: Reconsider force unwrapping.
  20. #if os(tvOS)
  21. return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
  22. #else
  23. return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
  24. #endif
  25. }
  26. /// Check if file is available at URL.
  27. static func isFileReachable(at fileURL: URL) -> Bool {
  28. do {
  29. let isReachable = try fileURL.checkResourceIsReachable()
  30. return isReachable
  31. } catch {
  32. print(error.localizedDescription)
  33. /// File unreachable.
  34. return false
  35. }
  36. }
  37. /// Move file at a location to another location.
  38. static func moveFile(at sourceURL: URL, to destinationURL: URL) throws {
  39. if isFileReachable(at: destinationURL) {
  40. do {
  41. try FileManager.default.removeItem(at: destinationURL)
  42. } catch {
  43. throw DownloadError
  44. .internalError(description: "Could not replace existing model file.")
  45. }
  46. }
  47. do {
  48. try FileManager.default.moveItem(at: sourceURL, to: destinationURL)
  49. } catch {
  50. throw DownloadError.internalError(description: "Unable to save model file.")
  51. }
  52. }
  53. }