【问题标题】:No such file or directory when saving record using CloudKit使用 CloudKit 保存记录时没有这样的文件或目录
【发布时间】:2016-11-13 22:46:54
【问题描述】:

我正在尝试将记录保存到 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 时,记录上传正常。但是,现在我收到以下错误:

打开错误:2(没有这样的文件或目录)

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

【问题讨论】:

    标签: ios swift file assets cloudkit


    【解决方案1】:

    您没有正确创建文件 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.")
    }
    

    我还强烈建议您在代码中避免使用所有 !。这些都是等待发生的崩溃。正确处理选项。所有这些强制展开都会导致问题。

    【讨论】:

      猜你喜欢
      • 2013-07-03
      • 1970-01-01
      • 2019-07-04
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2015-12-14
      相关资源
      最近更新 更多