iOS Guides | Samples

CloudKit Namespace

The CloudKit namespace provides access to iCloud.

Remarks

The CloudKit namespace allows application developers to control the flow of data between their applications and iCloud. iCloud provides server-side data storage, both "public" that is shared between all instances of an application or specific applications and "private" that is unique to a single user. iCloud storage and transport is encrypted and synchronized between Apple devices. CloudKit does not provide client-side persistence or data caching -- CloudKit functionality is only available while the user has an active Internet connection.

The highest-level class in the CloudKit is CKContainer. A CloudKit Container (sometimes referred to in Apple documentation as a "Ubiquity container") is an information store identified with a particular name. Apple advises using a name of the form "iCloud.{reverse DNS}.{appName}", for instance, "iCloud.com.mycompany.MyApp". Developers must create and configure their containers using the iCloud Dashboard, available by way of the Apple developer portal.

A single CKContainer may contain both public data, which is shared between all instances of the app (see CKContainer.PublicCloudDatabase), and private data, which contains user-specific data (see CKContainer.PrivateCloudDatabase). Within iCloud, public data is stored in the app's iCloud storage while private data is stored in the user's private iCloud storage. The public CKDatabase is available to all connected users of the app, whether or not they are logged in to iCloud. The private CKDatabase is only if the user is logged in to iCloud. Developers must write their code such that it reacts gracefully to changes in the user's login or connection status.

These public and private CKDatabase objects store structured records. These are represented by CKRecord objects. In addition to field-like key-value data, these records may hold CKAsset large objects either directly (retrieved with the containing CKRecord) or as references (allowing lazy retrieval of the large data).

All CKRecord instances are stored within a CKZone. A CKZone is something like a traditional database instance: it can contain multiple CKRecord stores that may refer to each other but not to stores in other CKZone instances and CKZone objects can be used to coordinate atomic operations across multiple CKRecord stores. The similarity to a database instance is not universal; for instance, a developer may use CKDatabase.FetchRecordAsync(CKRecordID) to retrieve a CKRecord directly from the CKDatabase without referring to the zone. The default CKZone is available via CKRecordZone.DefaultRecordZone. Developers may create additional zones using the CloudKit dashboard and use them to partition their data logically.

CloudKit apps require a provisioning profile with the com.apple.developer.icloud-services entitlement and an app-specific Bundle Identifier (e.g., "com.mycompany.CloudKitApp"). Developers must create and configure such an provisioning profile.

The following demonstrates some typical uses of CloudKit that work on single records:

C# Example

//Create 
private async Task<CKRecord> StoreInCloudKit (string name, CLLocation loc, int stationId)
{
    string containerName = "iCloud.com.xamarin.CKWork";
    var container = CKContainer.FromIdentifier (containerName);
    CKDatabase publicDatabase = container.PublicCloudDatabase;
    var zoneId = CKRecordZone.DefaultRecordZone ().ZoneId;
    var recordType = "StationReferences";

    var record = new CKRecord (recordType);
    record ["Name"] = new NSString (name);
    record ["Position"] = loc;
    record ["StationID"] = new NSNumber (stationId);

    var storedRecord = await publicDatabase.SaveRecordAsync (record);
    return storedRecord;
}

//Retrieve (via ID)
private async Task<CKRecord> AccessCloudKit ()
{
    string containerName = "iCloud.com.xamarin.CKWork";
    var container = CKContainer.FromIdentifier (containerName);
    CKDatabase publicDatabase = container.PublicCloudDatabase;

    var recordNameIHappenToKnow = "7eaf0432-2fa4-475f-851a-c6a19b3f8587";
    var recordId = new CKRecordID (recordNameIHappenToKnow);
    var record = await publicDatabase.FetchRecordAsync (recordId);

    return record;
}

//Retrieve (query)
private async Task<CKRecord []> QueryCloudKit ()
{
    string containerName = "iCloud.com.xamarin.CKWork";
    var container = CKContainer.FromIdentifier (containerName);
    CKDatabase publicDatabase = container.PublicCloudDatabase;
   
    var zoneId = CKRecordZone.DefaultRecordZone ().ZoneId;
    Console.WriteLine ($"Default zone name = '{zoneId.ZoneName}' owner = '{zoneId.OwnerName}'");
    /*
    var zoneName = "_defaultZone";
    var ownerName = "__defaultOwner__";
    var zoneId0 = new CKRecordZoneID (zoneName, ownerName);

    Console.WriteLine ($"Assert { zoneId0 == zoneId }");
    */

    var recordType = "StationReferences";

    var location = new CLLocation (19.7303, -155.056);
    var predicate = NSPredicate.FromFormat ("distanceToLocation:fromLocation:(Position, %@) < 100", location);

    var query = new CKQuery (recordType, predicate);

    var result = await publicDatabase.PerformQueryAsync (query, zoneId);
    return result;
}

//Update
private async Task<CKRecord> UpdateInCloudKit (CKDatabase database, CKRecord record, NSString key, NSObject newValue)
{
    record [key] = newValue;
    var modifiedRecord = await database.SaveRecordAsync (record);
    return modifiedRecord;
}

//Delete 
private async Task<CKRecordID> DeleteRecord (CKDatabase database, CKRecord record)
{
    var id = record.Id;
    var deletedId = await database.DeleteRecordAsync (id);
    return deletedId;
}

Classes

TypeReason
CKAcceptPerShareCompletionHandler
CKAcceptSharesOperationImplements an operation that accepts shared records.
CKAccountStatusEnumerates values that indicate whether a user's iCloud account is available.
CKApplicationPermissionsEnumerates a value that indicates that other app users can discover the current user by email address.
CKApplicationPermissionStatusEnumerates the states that an application can have when attempting to obtain a permission.
CKAssetA large file associated with a CKRecord object.
CKContainerEncapsulates content associated with an app, including shared and per-user private data.
CKContainer+Notifications
CKDatabaseContains data within a CKContainer. A public CKDatabase provides shared data, a private db holds the current user's data.
CKDatabaseDeleteSubscriptionHandlerCompletion handler for the CKDatabase.DeleteSubscription method.
CKDatabaseNotificationA notification about database activity.
CKDatabaseOperationAbstract class for operations on a CKDatabase.
CKDatabaseScopeEnumerates values that tell whether a database is private, shared, or public.
CKDatabaseSubscriptionA database subscription.
CKDiscoverAllContactsOperationA CKOperation that retrieves the IDs of all discoverable contacts of the app user.
CKDiscoverAllUserIdentitiesOperationAn operation that gets all of the discoverable users in the system's address book.
CKDiscoveredUserInfoInformation about a user. Returned by a T:CKDiscoverAllContactsOperation.
CKDiscoverUserIdentitiesOperationOperation that finds users that match a criterion.
CKDiscoverUserInfosCompletionHandlerApplication developers can implement this delgate and assign it to the CKDiscoverUserInfosOperation.Complete property to process the user information that is returned.
CKDiscoverUserInfosOperationA CKOperation that retrieves the IDs of discoverable users whose email addresses or record IDs are already known to the app dev.
CKErrorCodeEnumerates CloudKit error conditions.
CKErrorCodeExtensionsExtension methods for the CloudKit.CKErrorCode enumeration.
CKErrorFieldsHolds error constants used by CloudKit.
CKFetchDatabaseChangesCompletionHandler
CKFetchDatabaseChangesOperationAn operation that fetches database changes.
CKFetchNotificationChangesOperationA CKOperation that ret../../summary_set.sh CKFetchNotificationChangesOperation A
CKFetchPerShareMetadataHandler
CKFetchRecordChangesHandlerDelegate for the CKFetchRecordChangesOperation.AllChangesReported property.
CKFetchRecordChangesOperationA CKDatabaseOperation that retrieves data about changed or deleted CKRecord objects.
CKFetchRecordsCompletedHandlerDelegate for the CKFetchRecordsOperation.Completed property.
CKFetchRecordsOperationA CKDatabaseOperation that retrieves specific CKRecord objects.
CKFetchRecordZoneChangesFetchCompletedHandler
CKFetchRecordZoneChangesOperation
CKFetchRecordZoneChangesOptionsContains options that control how record zone changes are fetched.
CKFetchRecordZoneChangesTokensUpdatedHandler
CKFetchRecordZoneChangesWithIDWasDeletedHandler
CKFetchRecordZonesOperationA CKDatabaseOperation that retrieves CKRecordZone objects from iCloud.
CKFetchShareMetadataOperationAn operation that fetches shared metadata for multiple shares.
CKFetchShareParticipantsOperationAn operation that fetches shared participants for shared records.
CKFetchSubscriptionsCompleteHandlerDelegate for the CKFetchSubscriptionsOperation.Completed property.
CKFetchSubscriptionsOperationA CKDatabaseOperation that retrieves CKSubscription objects from iCloud.
CKFetchWebAuthTokenOperationOperation that returns a web authentication token for a specified API token from the CloudKit Dashboard.
CKFetchWebAuthTokenOperationHandler
CKLocationSortDescriptorSorts records based on their distance from the specified location.
CKMarkNotificationsReadHandlerDelegate for the CKMarkNotificationsReadOperation.Completed property.
CKMarkNotificationsReadOperationMarks push notifications as read. Typically used by apps that use push notifications to track record changes.
CKModifyBadgeOperationA CKOperation that modifies the badge of the app's icon, either on the current device or all the user's devices.
CKModifyRecordsOperationA CKDatabaseOperation that commits changes to one or more CKRecord objects.
CKModifyRecordsOperationHandlerDelegate for the CKModifyRecordsOperation.Completed property.
CKModifyRecordZonesHandlerDelegate for the CKModifyRecordZonesOperation.Completed property.
CKModifyRecordZonesOperationA CKDatabaseOperation that commits changes to record zones.
CKModifySubscriptionsHandlerDelegate for the CKModifySubscriptionsOperation.Completed property.
CKModifySubscriptionsOperationA CKDatabaseOperation that commits changes to one or more CKSubscription objects.
CKNotificationA push notification sent to the app.
CKNotificationIDUniquely identifies a push notification sent from a container.
CKNotificationInfoSpecifies the type of push notifications generated when the trigger condition is met.
CKNotificationTypeEnumerates the events that can generate a push notification.
CKOperationAbstract base class for operations executed against the CloudKit database.
CKQuerySpecifies a query against the CloudKit database.
CKQueryCursorHolds the current stopping point in the result set of a CKQuery.
CKQueryNotificationA push notification generated by a CKSubscription object.
CKQueryNotificationReasonEnumerates the persistent storage events that can trigger data lifecycle notifications.
CKQueryOperationA CKDatabaseOperation that executes a CKQuery.
CKQuerySubscription
CKQuerySubscriptionOptions
CKRecordA dictionary of Key-Value pairs that structure data within CloudKit.
CKRecordIDUniquely identifies a CKRecord within a database.
CKRecordSavePolicyEnumerates policies that control when or if a record should be saved.
CKRecordValueApp developers should not subclass this interface, which provides strong typing for objects stored in a CloudKit database. Custom data types are not supported.
CKRecordZoneAllows related CKRecord objects to be organized. By default, both the private and public database have a single zone.
CKRecordZoneCapabilitiesEnumerates the special operations that a zone is capable of.
CKRecordZoneCompleteHandlerDelegate for the CKFetchRecordZonesOperation.Completed property.
CKRecordZoneIDUniquely identifies a CKRecordZone within a database.
CKRecordZoneNotificationA push notification resulting from changes within a CKRecordZone.
CKRecordZoneSubscriptionA subscription to record zone changes.
CKReferenceDefines a 1:M relationship between CKRecord objects within a single CKRecordZone.
CKReferenceActionEnumerates values that control whether a reference should delete itself when its target record is deleted.
CKServerChangeTokenA read-only object that identifies a version of a CKRecord. When fetching updated data, passing the existing token allows the server to only return the changes, increasing efficiency.
CKShareRepresents a shared record.
CKShareKeys
CKShareMetadataRepresents shared record shared metadata.
CKShareParticipantContains data for a share participant.
CKShareParticipantAcceptanceStatusEnumerates responses to share participation requests.
CKShareParticipantPermissionEnumerates user share permissions.
CKShareParticipantTypeEnumerates share participant types.
CKSubscriptionA persistent query that tracks changes on the server. (See CKQueryNotification.)
CKSubscriptionOptionsEnumerates flags for controlling push notification behavior for query-based subscriptions.
CKSubscriptionTypeEnumerates subscription types.
CKUserIdentityContains information that is used to look up a user or users.
CKUserIdentityLookupInfoContains data that can be used to look up a user.
ICKRecordValueInterface representing the required methods (if any) of the protocol CKRecordValue.