This answer works with Swift 2.2 and iOS 9 and separates file creation from downloading, so you can test them correctly, as they represent different actions with their own potential problems.
For uploadPhoto, the recordType variable is the value that you use in the CloudKit dashboard. The "photo" key on the line photo["photo"] = asset is the name of the field for your post type.
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")
source share