2016-11-13 70 views
0

我正在嘗試將記錄保存到CloudKit。該記錄包含2個字符串,並且一個CKAsset包含UIImage。這是我創造的資產代碼:使用CloudKit保存記錄時沒有此類文件或目錄

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)

如何擺脫此錯誤並正確保存我的記錄?謝謝!

回答

2

您沒有正確創建文件的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.") 
} 

我也強烈建議你避免一切在你的代碼的!的。那些崩潰正在等待發生。妥善處理選擇權。所有這些強制解包都會導致問題。

相關問題