无法写入 IOS 上的 data.plist 文件

can't write to data.plist file on IOS

我的 ios 应用程序中有 data.plist 文件,我用它来存储用户首选项。我可以读取文件。但是我无法写入文件,并且在捕获时出现此错误。

注意:当我 运行 测试设备上的应用程序时发生错误

Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “data.plist” in the folder “MyApp”." UserInfo={NSFilePath=/private/var/containers/Bundle/Application/37FE297E-5801-4681-AA7C-6FCF9BAA9E87/MyApp.app/data.plist, NSUnderlyingError=0x283996880 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

func updateDataPlist(){

    self.thresholdForAdminBalances = Int(self.txtfThresholdForAdminBalances.text!)
    self.thresholdForSubUserbalances = Int(self.txtfThresholdForSubUserBalances.text!)

    let encoder = PropertyListEncoder()
    encoder.outputFormat = .xml

    let preferences =  Preferences(thresholdForAdminBalances: thresholdForAdminBalances!, thresholdForSubUserBalances: thresholdForSubUserbalances!)


    if let path = Bundle.main.url(forResource: "data", withExtension: "plist"){

        do {
            let data = try encoder.encode(preferences)
            try data.write(to: path)
        } catch {
            print(error)
        }
    }
}

You don’t have permission to save the file “data.plist” in the folder “MyApp”

您的应用程序包是只读的。将文件保存在可写目录之一中,例如文档或应用程序支持目录。

使用 Filemanager.url(for:in:appropriateFor:create:) 获取其中一个目录的 URL。