Created
February 29, 2016 21:44
-
-
Save MarcusSmith/60678bdd82480a1bdf00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageLoading.swift | |
// CloudKitDemo | |
// | |
// Created by Marcus Smith on 2/29/16. | |
// Copyright © 2016 FrozenFireStudios. All rights reserved. | |
// | |
import UIKit | |
import CloudKit | |
enum ImageSize { | |
case Thumbnail | |
case Medium | |
case Fullsize | |
var recordKey: String { | |
switch self { | |
case .Thumbnail: | |
return "thumbnail" | |
case .Medium: | |
return "medium" | |
case .Fullsize: | |
return "fullsize" | |
} | |
} | |
} | |
/// Completion returns the saved image's imageID if successful or an error if unsuccessful | |
func saveNewImageWithThumbnail(thumbnailImage: UIImage, mediumImage: UIImage, fullsizeImage: UIImage, completion: (imageID: String?, error: ErrorType?) -> Void) { | |
let newRecord = CKRecord(recordType: "image") | |
do { | |
newRecord[ImageSize.Thumbnail.recordKey] = try CKAsset(image: thumbnailImage) | |
newRecord[ImageSize.Medium.recordKey] = try CKAsset(image: mediumImage) | |
newRecord[ImageSize.Fullsize.recordKey] = try CKAsset(image: fullsizeImage) | |
CKContainer.defaultContainer().publicCloudDatabase.saveRecord(newRecord, completionHandler: { (record, error) -> Void in | |
if let recordID = record?.recordID.recordName { | |
completion(imageID: recordID, error: nil) | |
} | |
else { | |
completion(imageID: nil, error: error) | |
} | |
}) | |
} | |
catch { | |
completion(imageID: nil, error: error) | |
} | |
} | |
/// Completion returns an image if successful or an error if unsuccessful | |
func fetchImageWithID(imageID: String, imageSize: ImageSize, completion: (image: UIImage?, error: ErrorType?) -> Void) { | |
let imageRecordID = CKRecordID(recordName: imageID) | |
let fetchOperation = CKFetchRecordsOperation(recordIDs: [imageRecordID]) | |
fetchOperation.desiredKeys = [imageSize.recordKey] | |
fetchOperation.fetchRecordsCompletionBlock = { (records, error) in | |
if let imageRecord = records?[imageRecordID], asset = imageRecord[imageSize.recordKey] as? CKAsset, image = asset.image { | |
completion(image: image, error: nil) | |
} | |
else { | |
completion(image: nil, error: error) | |
} | |
} | |
CKContainer.defaultContainer().publicCloudDatabase.addOperation(fetchOperation) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment