⛅️
CombineCloudKit
Swift Combine extensions for asynchronous CloudKit record processing. Designed for simplicity.
CombineCloudKit exposes CloudKit operations as Combine publishers. Publishers can be used to process values over time, using Combine's declarative API.
Usage
CombineCloudKit is a Swift Package. Add a dependency on CombineCloudKit to your project using Xcode or the Swift Package Manager.
import PackageDescription
let package = Package(
name: "MyApp",
dependencies: [
.package(name: "CombineCloudKit", url: "https://github.com/chris-araman/CombineCloudKit.git", .upToNextMajor(from: "0.0.1"))
]
)
Combine allows you to chain value processing Publishers for one or more Subscribers. Here, we perform a query on our CKDatabase
, then process the results asynchronously. As each CKRecord
is read from the database, it is passed to the map
publisher which publishes the value of the record's name field. Any errors in the chain so far can be handled in the catch publisher, which passes CKRecordValue
values along to our sink
subscriber where the final values are processed.
import CloudKit
import Combine
import CombineCloudKit
func queryDueItems(database: CKDatabase, due: Date) {
let cancellable = database
.performQuery(ofType: "ToDoItem", where: NSPredicate(format: "due >= %@", due))
.map { record: CKRecord -> CKRecordValue in
// Map each ToDoItem to its Name
print("Received record: \(record)")
return record["Name"]
}.catch { error: Error in
// Handle any upstream error
print("Received error: \(error)")
}.sink { value: CKRecordValue in
// Process the Name of each ToDoItems
print("Received result: \(value)")
}
// ...
}
Note that the Cancellable
subscriber from sink
will cancel the upstream publishers when it is deinitialized. Take care to ensure that your subscribers live long enough to process values. If a CombineCloudKit publisher is cancelled before it is finished emitting values, the underlying CKOperation
will be cancelled. This may be desirable when performing a query and processing only the first few results. However, failing to wait for completion of a save
, delete
, or modify
operation may result in undesirable cancellation.
Building
swift build
Testing
swift test
swift test
. This is a work in progress. Once testing with entitlements is working, it is a goal to achieve > 90% code coverage.
Documentation
Further Reading
To learn more about Combine and CloudKit, watch these videos from WWDC:
...or review Apple's documentation:
License
CombineCloudKit was created by Chris Araman. It is published under the MIT license.