Locally cache CloudKit Subscription

Hello all,


In the CloudKit Best Practices session of WWDC 2016 (Session 231), it is often repeated that access to CloudKit is expensive and thus we should locally cache some items, such as the CloudKit subscriptions.


I performed this action pretty easily: First time the app is launched, I create the relevant CloudKit subscription to private database and I store with UserDefaults a boolean that states that I successfully created the subscription. So that, next time the app is launched, it does not have to perform the request (saving iCloud accesses).


However what would happen if we change the iCloud user on the device? I know this is a regular action but it is much possibble that a device is used by multiple users or, more likely, that a parent is giving his/her old device to kids. Anyway there is a way to change the iCloud account on a device.


I am tehrefore wondering how to deal with this situation? How could I ensure the following:

1. Locally cache the fact that a CloudKit subscription has already been performed for a specific iCloud account and thus prevent from redoing it for this iCloud account

2. Ensure that when the iCloud account has changed on this device, the app creates the relevant CloudKit subscription to the private database


I locally stored the CKCurrentUserDefaultName along with the boolean that indicates the subscription has been done but... This string is always the same regardless the iClound account that is used.


Any tip? Any help would be much appreciated.

Replies

I suggest you to user recordID in the method -[CKContainer fetchUserRecordIDWithCompletionHandler:] when you create a subscription. You should cache the user recordID. And next time when you see the curreent user recordID is different from the cached one, you can assume the iCloud account logged in has changed. Then you just create another subscription with the most recent user recordID.