Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of showing how to use CKDatabaseScope
import CloudKit
public enum CloudKitError: Error {
case general(String)
case emptyresult(String)
}
public enum CloudKitResult<T, ResultError: Error> {
case success(T)
case failure(ResultError)
}
public typealias CloudKitFetchClosure<T> = (_ result: CloudKitResult<T, CloudKitError>) -> Void
public typealias CloudKitSaveClosure = (_ success: Bool) -> Void
public final class CloudKitController {
// MARK: Public (typealises)
public typealias CKRecordType = CKRecord
public typealias CKRecordIDType = CKRecordID
public typealias CKUserIdentityType = CKUserIdentity
// MARK: Public (properties)
public let container: CKContainer = CKContainer.default()
public private(set) var publicDB: CKDatabase
public private(set) var privateDB: CKDatabase
// MARK: Private (properties)
fileprivate var scope: CKDatabaseScope
fileprivate var currentDatabase: CKDatabase {
return self.container.database(with: self.scope)
}
// MARK: Initializers
public init(scope: CKDatabaseScope) {
self.publicDB = self.container.publicCloudDatabase
self.privateDB = self.container.privateCloudDatabase
self.scope = scope
}
convenience public init() {
self.init(scope: .public)
}
// MARK: Public
public func save(_ record: CKRecord, callback: @escaping CloudKitFetchClosure<CKRecordType>) -> Void {
self.currentDatabase.save(record, completionHandler: {updatedRecord, error in
if let error: Error = error {
DispatchQueue.main.async(execute: {
callback(.failure(.general(error.localizedDescription)))
})
} else {
if let ckrecord: CKRecord = updatedRecord {
DispatchQueue.main.async(execute: {
callback(.success(ckrecord))
})
} else {
DispatchQueue.main.async(execute: {
callback(.failure(.emptyresult("There callback returned a nil object")))
})
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment