Setup & Container
Enable iCloud and CloudKit capability, then use a container and database.
Syntax:
let container = CKContainer.default()let db = container.privateCloudDatabase
Example
Setup.swift
ContentView.swift
App.swift
import CloudKit
let container = CKContainer.default()
let db = container.privateCloudDatabase
This prepares a handle to the user’s private database.
Save a Record
Create a CKRecord with fields and save it to the database.
Syntax:
let rec = CKRecord(recordType: "Type")db.save(rec) { ... }
Example
Save.swift
ContentView.swift
App.swift
import CloudKit
func addNote(title: String, body: String, completion: @escaping (Result) -> Void) {
let rec = CKRecord(recordType: "Note")
rec["title"] = title as CKRecordValue
rec["body"] = body as CKRecordValue
CKContainer.default().privateCloudDatabase.save(rec) { saved, err in
if let saved = saved { completion(.success(saved)) } else { completion(.failure(err!)) }
}
}
This example writes a simple Note record into the private database.
Query Records
Fetch records matching a predicate using CKQuery.
Syntax:
CKQuery(recordType:predicate:)db.perform(query, inZoneWith:)
Example
Query.swift
ContentView.swift
App.swift
import CloudKit
func loadNotes(completion: @escaping (Result<[CKRecord], Error>) -> Void) {
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Note", predicate: predicate)
CKContainer.default().privateCloudDatabase.perform(query, inZoneWith: nil) { records, err in
if let records = records { completion(.success(records)) } else { completion(.failure(err!)) }
}
}
Leave a Reply