使用 CloudKit 保存记录时没有这样的文件或目录

No such file or directory when saving record using CloudKit

我正在尝试将记录保存到 CloudKit。该记录包含 2 个字符串,一个 CKAsset 包含 UIImage。这是我创建资产的代码:

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let filePath = "file://\(path)/NewPicture.jpg"

do {
    try UIImageJPEGRepresentation(newPicture!, 1)!.write(to: URL(string: filePath)!)
} catch {
    print("Error saving image to URL")
    print(error)
    self.errorAlert(message: "An error occurred uploading the image. Please try again later.")
}

let asset = CKAsset(fileURL: URL(string: filePath)!)
record.setObject(asset, forKey: "picture")

当我不使用 CKAsset 时,记录上传正常。但是,现在我收到以下错误:

open error: 2 (No such file or directory)

我怎样才能摆脱这个错误并正确保存我的记录?谢谢!

您没有正确创建文件 URL。

并将创建和使用 CKAsset 的代码移动到应该使用的地方。

你想要:

let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = docURL.appendingPathComponent("NewPicture.jpg")

do {
    try UIImageJPEGRepresentation(newPicture!, 1)!.write(to: fileURL)
    let asset = CKAsset(fileURL: fileURL)
    record.setObject(asset, forKey: "picture")
} catch {
    print("Error saving image to URL")
    print(error)
    self.errorAlert(message: "An error occurred uploading the image. Please try again later.")
}

我还强烈建议您在代码中避免所有这些 !。这些都是等待发生的崩溃。妥善处理可选项。所有这些强制解包都会导致问题。