xcode 如何使用swift上传带有云套件的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29417778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload images with cloud kit using swift?
提问by nachshon f
How do I upload and load back images from cloud kit with swift?
如何使用 swift 从云套件上传和加载图像?
What attribute type do I use?
我使用什么属性类型?
What code do I use? This is the code I use currently...
我使用什么代码?这是我目前使用的代码...
func SaveImageInCloud(ImageToSave: UIImage) {
let newRecord:CKRecord = CKRecord(recordType: "ImageRecord")
newRecord.setValue(ImageToSave, forKey: "Image")
if let database = self.privateDatabase {
database.saveRecord(newRecord, completionHandler: { (record:CKRecord!, error:NSError! ) in
if error != nil {
NSLog(error.localizedDescription)
}
else {
dispatch_async(dispatch_get_main_queue()) {
println("finished")
}
}
})
}
采纳答案by Edwin Vermeer
You need to create a CKAsset and add that to your record. You can do that with code like this:
您需要创建一个 CKAsset 并将其添加到您的记录中。你可以用这样的代码做到这一点:
func SaveImageInCloud(ImageToSave: UIImage) {
let newRecord:CKRecord = CKRecord(recordType: "ImageRecord")
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(ImageToSave).writeToFile(writePath, atomically: true)
var File : CKAsset? = CKAsset(fileURL: NSURL(fileURLWithPath: writePath))
newRecord.setValue(File, forKey: "Image")
}
}
}
if let database = self.privateDatabase {
database.saveRecord(newRecord, completionHandler: { (record:CKRecord!, error:NSError! ) in
if error != nil {
NSLog(error.localizedDescription)
} else {
dispatch_async(dispatch_get_main_queue()) {
println("finished")
}
}
})
}
回答by William T.
Here's something similar to Edwin's answer but a little more compact. I've tested this and it works well.
这是类似于埃德温的答案,但更紧凑一些。我已经对此进行了测试,并且效果很好。
This example is saving "myImage" UIImageView into "mySaveRecord" CKRecord, just replace those names with your respective ones.
此示例将“myImage” UIImageView 保存到“mySaveRecord”CKRecord 中,只需将这些名称替换为您各自的名称即可。
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let imageFilePath = documentDirectory.stringByAppendingPathComponent("lastimage")
UIImagePNGRepresentation(myImage).writeToFile(imageFilePath, atomically: true)
let asset = CKAsset(fileURL: NSURL(fileURLWithPath: imageFilePath))
mySaveRecord.setObject(asset, forKey: "ProfilePicture")
CKContainer.defaultContainer().publicCloudDatabase.saveRecord(mySaveRecord, completionHandler: {
record, error in
if error != nil {
println("\(error)")
} else {
//record saved successfully!
}
})
回答by CodeBender
This answer works with Swift 2.2 & iOS 9, and separates the file creation from the upload so that you can properly test against both, since they are distinct actions with their own potential issues.
此答案适用于 Swift 2.2 和 iOS 9,并将文件创建与上传分开,以便您可以对两者进行正确测试,因为它们是具有各自潜在问题的不同操作。
For the uploadPhoto function, the recordType variable is the value you use in your CloudKit dashboard. The "photo" key in the photo["photo"] = asset
line is the field name for your record type.
对于uploadPhoto 函数,recordType 变量是您在CloudKit 仪表板中使用的值。该行中的“照片”键photo["photo"] = asset
是您的记录类型的字段名称。
func uploadPhoto(image: UIImage, recordName: String) {
let privateDB = CKContainer.defaultContainer().privateCloudDatabase
let photoID = CKRecordID(recordName: recordName)
let photo = CKRecord(recordType: recordType, recordID: photoID)
let asset = CKAsset(fileURL: writeImage(image))
photo["photo"] = asset
privateDB.saveRecord(photo) { (record, error) in
guard error == nil else {
print(error?.localizedDescription)
return
}
print("Successful")
}
}
func writeImage(image: UIImage) -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let fileURL = documentsURL.URLByAppendingPathComponent(NSUUID().UUIDString + ".png")
if let imageData = UIImagePNGRepresentation(image) {
imageData.writeToURL(fileURL, atomically: false)
}
return fileURL
}
You can call this with the following:
您可以使用以下命令调用它:
uploadPhoto(UIImage(named: "foo.png")!, recordName: "bar")
回答by farktronix
You'll want to pick the Asset value type in the dashboard for this value.
您需要在仪表板中为该值选择资产值类型。
newRecord.setValue(ImageToSave, forKey: "Image")
newRecord.setValue(ImageToSave, forKey: "Image")
UIImage is not an allowed type on CKRecord
. Your best option is to write this image out to a file, then create a CKAsset
and set that on the record.
UIImage 不是 上允许的类型CKRecord
。您最好的选择是将此图像写入文件,然后创建一个CKAsset
并将其设置在记录中。