How to encode/decode [CKRecordZone.ID: CKServerChangeToken]?

public var zonesChangeToken: [CKRecordZone.ID: CKServerChangeToken]? {
  get {
  if(backingPreviousZonesChangeToken == nil) {
  guard let defaults: UserDefaults = UserDefaults(suiteName: CloudKitHandler.APP_GROUP_ID) else { return nil }
  guard let data = defaults.data(forKey: CloudKitHandler.CK_PREVIOUS_ZONES_CHANGE_TOKEN)
  else { return [CKRecordZone.ID: CKServerChangeToken]() }
  do {
  let unarchiver: NSKeyedUnarchiver = try NSKeyedUnarchiver(forReadingFrom: data)
  unarchiver.requiresSecureCoding = true
  backingPreviousZonesChangeToken = try unarchiver.decodeTopLevelObject() as? [CKRecordZone.ID: CKServerChangeToken]
  } catch { }
  }

  return backingPreviousZonesChangeToken
  }

  set(value) {
  backingPreviousZonesChangeToken = value
  guard let value = value else { return }
  guard let defaults: UserDefaults = UserDefaults(suiteName: CloudKitHandler.APP_GROUP_ID) else { return }
  let archiver: NSKeyedArchiver = NSKeyedArchiver(requiringSecureCoding: true)
  archiver.encode(value)
  archiver.finishEncoding()
  defaults.setValue(archiver.encodedData, forKey: CloudKitHandler.CK_PREVIOUS_ZONES_CHANGE_TOKEN)

  }
  }


I'm trying to encode/decode a dictionary of IDs and Tokens. But for some reason the decode always gives me a nil.

How to fix?


Error Domain=NSCocoaErrorDomain Code=4864 "value for key '$0' was of unexpected class 'NSDictionary'. Allowed classes are '(null)'." UserInfo={NSDebugDescription=value for key '$0' was of unexpected class 'NSDictionary'. Allowed classes are '(null)'.}

I use these with success:

Get

let tokenData = // stored locally

let token = try NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: tokenData)


Set

let token: CKServerChangeToken? = the token from CK to be stored locally

let tokenData = try NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: false)

// store tokenData locally

How to encode/decode [CKRecordZone.ID: CKServerChangeToken]?
 
 
Q