Reputation: 1594
I wrote the code below to share a CKRecord:
CKRecordZone *restaurantsZone = [[CKRecordZone alloc] initWithZoneName:@"RestaurantsZone"];
CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:self.recordName zoneID:restaurantsZone.zoneID];
CKRecord *record = [[CKRecord alloc] initWithRecordType:@"Restaurant" recordID:recordID];
[record setValue:self.restaurant forKey:@"name"];
UICloudSharingController *cloudSharingController = [[UICloudSharingController alloc] initWithPreparationHandler:^(UICloudSharingController * _Nonnull controller, void (^ _Nonnull preparationCompletionHandler)(CKShare * _Nullable, CKContainer * _Nullable, NSError * _Nullable)) {
[self shareRootRecord:record name:self.restaurant completion:preparationCompletionHandler];
}];
cloudSharingController.delegate = self;
[self presentViewController:cloudSharingController animated:YES completion:nil];
And the shareRootRecord
function:
- (void)shareRootRecord:(CKRecord *)rootRecord name:(NSString *)name completion:(void (^)(CKShare * _Nullable share, CKContainer * _Nullable container, NSError * _Nullable error))completion
{
CKShare *shareRecord = [[CKShare alloc] initWithRootRecord:rootRecord];
shareRecord[CKShareTitleKey] = name;
NSArray *recordsToSave = @[rootRecord, shareRecord];
CKContainer *container = [CKContainer defaultContainer];
CKDatabase *privateDatabase = [container sharedCloudDatabase];
CKModifyRecordsOperation *operation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:@[]];
[operation setPerRecordCompletionBlock:^(CKRecord * _Nullable record, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", [error localizedDescription]);
}
}];
[operation setModifyRecordsCompletionBlock:^(NSArray<CKRecord *> * _Nullable savedRecords, NSArray<CKRecordID *> * _Nullable deletedRecordIDs, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", [error localizedDescription]);
}
completion(shareRecord, container, error);
}];
[privateDatabase addOperation:operation];
}
Now, when I run this code, the following error is thrown: Only shared zones can be accessed in the shared DB
. I can't seem to be able to figure out why, though. Any ideas?
Upvotes: 0
Views: 414
Reputation: 43
Make sure the CKRecord
you want to share is already in the owners privateDB before you share it.
When a participant accepts the share, that's when the record will appear in the participants sharedDB.
This code creates a record and a share and then tries to modify the sharedDB of the owner with the records.
Conceptually, you want to share a a record in an owners privateDB with a participant. The sharedDB of a participant acts as a window into the privateDB of the owner.
Upvotes: 1