简体   繁体   English

读取并更新到主应用程序包中的 JSON 文件

[英]Read and Update into JSON file in main app bundle

I have a JSON file witch copied locally into xcode which I can read it through the main bundle.我有一个 JSON 文件,它在本地复制到 xcode 中,我可以通过主包读取它。 But then I have problem update this JSON file because everytime i write into a new JSON file create in app document folder.但是我在更新这个 JSON 文件时遇到问题,因为每次我写入一个新的 JSON 文件时,都会在应用程序文件夹中创建。

Here are the sample JSON file这是示例 JSON 文件

[
{
    "id": "5c8a80f52dfee238898d64cf",
    "firstName": "Phoebe",
    "lastName": "Monroe",
    "email": "phoebemonroe@furnafix.com",
    "phone": "(903) 553-3410"
},
{
    "id": "5c8a80f575270ddb54a18f86",
    "firstName": "Lidia",
    "lastName": "Wilkins",
    "email": "lidiawilkins@furnafix.com",
    "phone": "(997) 482-3866"
}
]

Here are the code which I update the JSON file这是我更新 JSON 文件的代码

  let mainUrl = Bundle.main.url(forResource: "data", withExtension: ".json")!

    let json = JSON(contact)
    let hello = json.arrayObject
    let str = hello?.description
    let data = str!.data(using: String.Encoding.utf8)!
    do{
    try data.write(to: mainUrl, options: [])
        } catch {
                print(error)
}
}

You can't save the file in main bundle again as it's read-only, you need to copy it to say documents/library folder where you can read/write您不能再次将文件保存在主包中,因为它是只读的,您需要将其复制到可以读/写的文档/库文件夹中


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let from = Bundle.main.url(forResource: "data", withExtension: "json")!

        let to = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("result.json")

        do {

            try FileManager.default.copyItem(at: from, to: to)

            print(try FileManager.default.contents(atPath: to.path))

            let wer = Data("rerree".utf8 )

            try wer.write(to: to)

            print(try FileManager.default.contents(atPath: to.path))

        }
        catch {

            print(error)
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM