Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Persisting Change Tokens for CloudKit Sync
// MARK: - Storing and Accessing Change Tokens
fileprivate extension UserDefaults {
fileprivate func setUUID(_ uuid: UUID, using key: String) {
self.set(uuid.uuidString, forKey: key)
fileprivate func uuid(matching key: String) -> UUID? {
guard let str = UserDefaults.standard.string(forKey: key) else {
os_log("** UUID not found: %@", log: log, key)
return nil
guard let uuid = UUID(uuidString: str) else {
os_log("** decoding UUID failed: %@",log: log, key)
return nil
return uuid
fileprivate func setServerChangeToken(_ token: CKServerChangeToken, using key: String) {
let coder = NSKeyedArchiver(requiringSecureCoding: true)
token.encode(with: coder)
self.set(coder.encodedData, forKey: key)
fileprivate func serverChangeToken(matching key: String) -> CKServerChangeToken? {
guard let data = UserDefaults.standard.object(forKey: key) as? Data else {
os_log("** server change token not found: %@", log: log, key)
return nil
do {
let coder = try NSKeyedUnarchiver(forReadingFrom: data)
coder.requiresSecureCoding = true
return CKServerChangeToken(coder: coder)
} catch {
os_log("** decoding server change token failed: ( %@, %@ )",
log: log, key, error as CVarArg)
return nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.