[英]How to write JSON to file locally with FileManger and JSONEncoder? Swift
所以我想做的是將代碼中創建的 json 寫入用戶本地文檔目錄,但似乎可以讓它工作。
struct Puzzle: Codable {
let id: Int?
let puzzle: Int?
let moves: Int?
}
class PuzzleController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create reference to default filemanager object
let filemgr = FileManager.default
// get documents directory path
let dirPath = filemgr.urls(for: .documentsDirectory, in: .userDomainMask)
let docsDir = dirPath[0].path
// change to current working directory
filemgr.changeCurrentDirectoryPath(docsDir)
// create a new directory
let docsURL = dirPath[0]
let newDir = docsURL.appendingPathComponent("json").path
do {
try filemgr.createDirectory(atPath: newDir, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizeDescription)
}
// create arrary of json objects
let jsonPuzzle = [Puzzle(id: 1, puzzle: 1, moves: 1), Puzzle(id: 2, puzzle: 2, moves: 2), Puzzle(id: 3, puzzle: 3, moves: 3)]
// create url to json file
let jURL = URL(string: newDir)?.appendingPathComponent("pjson.json")
// write to json file
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try encoder.encode(jsonPuzzle)
try jsonData.write(to: jURL)
} catch let jError {
print(jError)
}
}
}
我不斷收到 CFURLCopyResourcePropertyForKey 失敗,因為它傳遞了一個沒有方案的 URL 和錯誤 Domain=NSCocoaErrorDomain Code=518 “無法保存文件,因為不支持指定的 URL 類型。”
我究竟做錯了什么? 在不使用第三方 api 的情況下,將 json 寫入本地文件所需的正確步驟是什么?
其中一位評論者要求的 jURL 內容。 “/Users/blank/Library/Developer/CoreSimulator/Devices/920F6A0F-E814-49E2-A792-04605361F139/data/Containers/Data/Applicatio ... ir/pjson”
問題是,當您在路徑的URL
和String
之間來回切換時,您會丟失協議(方案),僅使用URL
將修復您的錯誤。
這是您的代碼的縮短版本,僅使用URL
作為目錄和文件路徑,以確保 URL 有效
let filemgr = FileManager.default
let dirPath = filemgr.urls(for: .documentsDirectory, in: .userDomainMask)
let docsURL = dirPath[0]
let newDir = docsURL.appendingPathComponent("json")
do {
try filemgr.createDirectory(at: newDir, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
let jURL = newDir.appendingPathComponent("pjson.json")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.