ios - 如何将图像作为 CKAsset 正确发送到 CloudKit?

标签 ios cloudkit

我有一个图像(UIImage 和它的 url),我试图将它作为 CKAsset 发送到 CloudKit,但我遇到了这个错误:Terminating app due to uncaught exception 'NSInvalidArgumentException',原因: “非文件 URL”。这是代码:

override func viewDidLoad() {
        super.viewDidLoad()

        send2Cloud()
    }

func send2Cloud() {
    let newUser = CKRecord(recordType: "User")

    let url = NSURL(string: self.photoURL)

    let asset = CKAsset(fileURL: url!)

    newUser["name"] = self.name
    newUser["photo"] = asset

    let publicData = CKContainer.defaultContainer().publicCloudDatabase

    publicData.saveRecord(newUser, completionHandler: { (record: CKRecord?, error: NSError?) in

        if error == nil {

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                print("User saved")
            })

        } else {
            print(error?.localizedDescription)
        }
    })
}

我有 URL,我可以打印它,复制并粘贴到我的导航器,它会显示我的图像!所以,我不知道这里发生了什么......

如果我使用 UIImage 而不是它的 URL 会更容易吗?因为,正如我之前所说,我两者都有!非常感谢任何帮助!谢谢,伙计们!!

最佳答案

根据我的经验,将上传 UIImage 保存为 CKAsset 的唯一方法是:

  1. 将图像临时保存到磁盘
  2. 创建 CKAsset
  3. 删除临时文件

let data = UIImagePNGRepresentation(myImage); // UIImage -> NSData, see also UIImageJPEGRepresentation
let url = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(NSUUID().UUIDString+".dat")
do {
    try data!.writeToURL(url, options: [])
} catch let e as NSError {
    print("Error! \(e)");
    return
}
newUser["photo"] = CKAsset(fileURL: url)

// ...

publicData.saveRecord(newUser, completionHandler: { (record: CKRecord?, error: NSError?) in
    // Delete the temporary file
    do { try NSFileManager.defaultManager().removeItemAtURL(url) }
    catch let e { print("Error deleting temp file: \(e)") }

    // ...
}


几个月前,我提交了一份错误报告,要求能够从内存中的 NSData 初始化 CKAsset,但尚未完成。

关于ios - 如何将图像作为 CKAsset 正确发送到 CloudKit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969341/

相关文章:

ios - 代码设计错误 : Provisioning profile cannot be found after deleting expired profile

ios - 使用带有自签名证书的 MPMoviePlayerController

ios - CloudKit 通知

ios - 如何从cloudkit下载多条记录

ios - 我可以将 CKRecords 从一个 CKContainer 移动到另一个 CKContainer 吗?

swift - 通过按钮强制与 iCloud 同步

objective-c - UITextField rightViewMode 奇怪的行为

ios - 当键盘显示时移动 UITextFields

ios - UITableViewCell黑色背景

swift - CloudKit - 每次运行相同的查询时,CKQueryOperation 结果都不同