Search code examples
iosxcodeswifticloudcloudkit

How to receive an image from cloudkit?


I am using this code to store an image in icloud, but what code do i use to retrieave it and place it in a UIImageView? I've tried everything, but it wont work?

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

Solution

  • Just read the CKRecord that you wrote and you can get the CKAsset by reading the key Image. You can get a UIImage using the code below.

    var file : CKAsset? = record.objectForKey("Image")
    
    func image() -> UIImage? {
        if let file = file {
            if let data = NSData(contentsOfURL: file.fileURL) {
                return UIImage(data: data)
            }
        }
        return nil
    }