penatheboss penatheboss - 21 days ago 16
iOS Question

No such file or directory when saving record using CloudKit

I am trying to save a record to CloudKit. The record contains 2 strings, and one

CKAsset
that holds a
UIImage
. Here is my code for creating the asset:

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")


When I was not using a
CKAsset
, the record was uploaded fine. However, now I get the following error:


open error: 2 (No such file or directory)


How can I get rid of this error and save my record correctly? Thanks!

Answer

You are not creating the file URL correctly.

And move the code to create and use the CKAsset to where it should be used.

You want:

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.")
}

I also strongly urge you to avoid all of those ! in your code. Those are crashes waiting to happen. Properly deal with optionals. All of that forced unwrapping is going to cause problems.

Comments