cloudkit: how to access main user's attributes

2019-06-07 16:52发布

问题:

I am trying to make an app in which every user would have a personal avatar, a nickname and so on.

I don't know how to access the user's account on cloudkit.

My solution would be to retrieve user's AppleID, query Cloudkit and modify the user's attribute... But I guess there should be a better way to do it. Isn't their something like NSUserDefault but for cloudkit?

回答1:

You first have to find out what the current loged in userId is. You can do that by executing the fetchUserRecordIDWithCompletionHandler method on the container. Then you can get more (currently only first and last name) information by executing the discoverUserInfoWithUserRecordID on that container.

You could extend the Users table with extra custom fields, but I would not advice doing that. The Users table is a special system table with some limitations. It would be better to create a separate recordType with the user settings. Just add a CKReference to the users table for easy access.

You also have to be aware that a user could log out and log in with a different iCloud account during the operation of your app. You could capture this by executing the code below right after your application start. Of course you have to implement your own logic where you see the NSLog

    var ubiquityIdentityDidChangeNotificationToken = NSNotificationCenter.defaultCenter().addObserverForName(NSUbiquityIdentityDidChangeNotification, object: nil, queue: nil) { _ in
        NSLog("The user’s iCloud login changed: should refresh all user data.")
    }