Created
April 12, 2017 00:53
-
-
Save paulw11/168990607ed4250a163b344e29402a60 to your computer and use it in GitHub Desktop.
Sample cloud kit asset list saving
This file contains hidden or 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
// | |
// ViewController.swift | |
// AssetSyncTest | |
// | |
// Created by Paul Wilkinson on 12/4/17. | |
// Copyright © 2017 Paul Wilkinson. All rights reserved. | |
// | |
import UIKit | |
import CloudKit | |
class ViewController: UIViewController { | |
var container: CKContainer! | |
var publicDB: CKDatabase! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
container = CKContainer.default() | |
publicDB = container.publicCloudDatabase | |
self.doStuff() | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func doStuff() { | |
let image1 = #imageLiteral(resourceName: "sample1") | |
let image2 = #imageLiteral(resourceName: "sample2") | |
if let asset1 = createAsset(from: UIImagePNGRepresentation(image1)!), | |
let asset2 = createAsset(from: UIImagePNGRepresentation(image2)!) { | |
let record = CKRecord(recordType: "test") | |
let assets = [asset1,asset2] | |
record["assets"] = assets as CKRecordValue | |
self.saveRecord(record) | |
} | |
} | |
func saveRecord(_ xrecord: CKRecord) { | |
let record: [CKRecord] = [xrecord] | |
let saveOperation = CKModifyRecordsOperation.init(recordsToSave: record, recordIDsToDelete: nil) | |
saveOperation.perRecordCompletionBlock = {(record, error) -> Void in | |
if let error = error { | |
print("error saving record: \(error)") | |
} | |
} | |
saveOperation.modifyRecordsCompletionBlock = {(records,ids,error) -> Void in | |
if let error = error { | |
print("Error saving records: \(error)") | |
} | |
} | |
publicDB.add(saveOperation) | |
} | |
func createAsset(from data: Data) -> CKAsset? { | |
var returnAsset: CKAsset? = nil | |
let tempStr = ProcessInfo.processInfo.globallyUniqueString | |
let filename = "\(tempStr)_file.bin" | |
let baseURL = URL(fileURLWithPath: NSTemporaryDirectory()) | |
let fileURL = baseURL.appendingPathComponent(filename, isDirectory: false) | |
do { | |
try data.write(to: fileURL, options: [.atomicWrite]) | |
returnAsset = CKAsset(fileURL: fileURL) | |
} catch { | |
print("Error creating asset: \(error)") | |
} | |
return returnAsset | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment