无法共享CKRecord

时间:2017-12-07 20:31:06

标签: ios objective-c cloudkit

我写了下面的代码来分享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];

shareRootRecord函数:

- (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];
}

现在,当我运行此代码时,会抛出以下错误:Only shared zones can be accessed in the shared DB。但我似乎无法弄明白为什么。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在共享之前,请确保您要共享的CKRecord已在所有者privateDB中。

当参与者接受共享时,记录将出现在参与者sharedDB中。

此代码创建记录和共享,然后尝试使用记录修改所有者的sharedDB。

从概念上讲,您希望与参与者共享所有者privateDB中的记录。参与者的sharedDB充当所有者的privateDB的窗口。