CloudKit relationships CKReference setup and query.

1.1k views Asked by At

I’m allowing Users to save locations. It is saving in cloudKit, I can fetch all the locations successfully. For each location saved there is a record who created it "created by: IDXXX". How do I pull all the locations saved by the single user who created it?

In CloudKit I have 2 record types, Location and Users. When a location is saved it is saved as a Location and I add a reference to the User’s record ID using CKReference to a field in Location that I have marked as “owningList” for attribute name with attribute type “Reference”. This method below is being called when a new location is saved grabbing the new saved location's CKRecord.

- (void)saveLocationToUserWithLocationRecord:(CKRecord *)locRecord {

    CKReference *ref  = [[CKReference alloc] initWithRecordID:self.userRecordID action:CKReferenceActionDeleteSelf];

    [locRecord setObject:ref forKey:@"owningList"];

}

Then I try to fetch all the locations with predicate specifying the CKReference which is the user’s Record ID and the field name “owningList” and this returns no result. I tried other ways without success. I’m very new to this any help or clarification would be greatly appreciated.

-(void)fetchUsersSavedLocations:(CKRecordID *)ID {

    CKDatabase *database = [[CKContainer defaultContainer] publicCloudDatabase];

    CKReference* recordToMatch = [[CKReference alloc] initWithRecordID:ID

                                                                action:CKReferenceActionDeleteSelf];

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"owningList", recordToMatch];

    CKQuery* query = [[CKQuery alloc] initWithRecordType:@"Location" predicate:predicate];

    [database performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {

        if (!error) {
            NSLog(@"SUCCESS results %@”, results);
        }
        else {
            NSLog(@"failed with error %@", error);
        }

    }];

}
0

There are 0 answers