如何将映像作为CKAsset正确发送到CloudKit? [英] How to properly send an image to CloudKit as CKAsset?
问题描述
我有一个图像(UIImage及其URL),我试图将其作为CKAsset发送到CloudKit,但出现此错误:由于未捕获的异常'NSInvalidArgumentException',正在终止应用程序,原因:非文件URL
。这是代码:
I have an image (UIImage and it's url too) and I'm trying to send it to CloudKit as a CKAsset but I'm having this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Non-file URL'
. Here is the code:
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,可以打印,复制并粘贴到导航器中d将显示我的图像!所以,我不知道这里发生了什么...
I have the URL, I can print it, copy and paste to my navigator and it will show my image! So, I don't know what is happening here...
如果我使用UIImage而不是URL会更容易吗?因为,正如我之前所说,我两个都有!任何帮助都非常感谢!谢谢大家!
It would be easier if I worked with an UIImage instead of it's URL? Because, as I sais before, I have both of them! Any help is very appreciated! Thanks, guys!!
推荐答案
根据我的经验,保存上载 UIImage $的唯一方法c $ c>作为
CKAsset
的目的是:
In my experience, the only way to save upload UIImage
as a CKAsset
is to:
- 将图像临时保存到磁盘
- 创建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
,但尚未完成。
I filed a bug report a few months ago requesting the ability to initialize
CKAsset
from in-memory NSData
, but it hasn't been done yet.
这篇关于如何将映像作为CKAsset正确发送到CloudKit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!