保存json WatchOS

时间:2019-03-05 20:35:51

标签: json swift xcode persistent

我正在尝试将具有某种数据结构的json保存到我的WatchOS应用中:

enum Directory {
  case documents
  case caches
}  
static fileprivate func getURL(for directory: Directory) -> URL {
    var searchPathDirectory: FileManager.SearchPathDirectory

    switch directory {
    case .documents:
        searchPathDirectory = .documentDirectory
    case .caches:
        searchPathDirectory = .cachesDirectory
    }

    if let url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).last {
        return url
    } else {
        fatalError("Could not create URL for specified directory!")
    }
}
static func store<T: Encodable>(_ object: T, to directory: Directory, as fileName: String) {
    let url = getURL(for: directory).appendingPathComponent(fileName, isDirectory: false)

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    do {
        let data = try encoder.encode(object)
        if FileManager.default.fileExists(atPath: url.path) {
            try FileManager.default.removeItem(at: url)
        }
        FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil)
    } catch {
        fatalError(error.localizedDescription)
    }
}

但是当我在Apple Watch上强制退出应用程序或等待1天时... json被删除。我究竟做错了什么?谢谢

0 个答案:

没有答案