我有一个图像(UIImage及其URL),并且试图将其作为CKAsset发送到CloudKit,但出现此错误:Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Non-file 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)
        }
    })
}

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

如果使用UIImage而不是URL会更容易?因为,正如我之前所说,我两个都有!任何帮助,我们将不胜感激!谢谢你们!!

最佳答案

以我的经验,将上载UIImage保存为CKAsset的唯一方法是:

  • 将图像临时保存到磁盘
  • 创建CKAsset
  • 删除临时文件

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

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

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

    10-10 05:13