nachshon fertel nachshon fertel - 4 months ago 43
iOS Question

How to upload images with cloud kit using swift?

How do I upload and load back images from cloud kit with swift?

What attribute type do I use?

enter image description here

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")

}
}
})
}

Answer

You need to create a CKAsset and add that to your record. You can do that with code like this:

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")
                }
            }
        })
    }