使用CloudKit保存记录时没有此类文件或目录

时间:2016-11-13 22:46:55

标签: ios swift file assets 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时,记录上传得很好。但是,现在我收到以下错误:

  

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

如何摆脱此错误并正确保存我的记录?谢谢!

1 个答案:

答案 0 :(得分:2)

您没有正确创建文件网址。

移动代码以创建并使用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.")
}

我还强烈建议您避免代码中的所有!。那些崩溃等待发生。妥善处理期权。所有强迫解缠都会导致问题。

相关问题