Restrict access to or lift restrictions on a user's data at their request.
Users can ask you to prevent any further changes to their data stored by your app in CloudKit. Use the restrict API provided by CloudKit Web Services to honor those requests. You can lift restrictions at the user's request by calling the unrestrict API.
To be sure that you'll be restricting changes and access to all of a user's data stored by your app, first cross-reference the list of containers your app has access to in Xcode and assemble a list of those containers' identifiers. This process is described in Identifying an App's Containers.
The example below stores containers in constants to be used later.
Create Reusable API Tokens
The restrict API call requires a token each time you call the API. You create an API token once for each container in your app using the CloudKit Dashboard and reuse it in each API call to a specific container.
Generate a token in the CloudKit Dashboard by visiting the page for each container, then selecting API Access > New Token > Create Token. Tokens are specific to a deployment environment, so separate tokens are required for the production and development environments.
The example below stores tokens in a dictionary associated with each container for use later.
Create Web Authentication Tokens
The restrict API call requires a new authentication token each time you call the API in addition to the reusable API token. The example below shows how to create that token by using a CKFetchWebAuthTokenOperation.
Once the authentication token is received, you can immediately call the restrict API once for each container.
Restrict Data Access in Each Container
The example below defines the restrict(container:apiToken:webToken:completionHandler:) and requestRestriction(url:completionHandler:) methods used in the example above to build the network request for the restrict API.
When a user requests that you undo restrictions, you use the unrestrict API, which performs the opposite operation that the restrict API performs.
The example below shows a modification of the restrict(container:apiToken:webToken:completionHandler:) method used above that lifts restrictions instead of enabling them.
A successful call to the unrestrict(container:apiToken:webToken: completionHandler:) function—indicated by a nil error parameter in the completion handler—means that your app's subsequent uses of CloudKit can access and modify user data once again.