WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

Getting Private User Record in CloudKit

I am attempting to get a Users' saved data in CloudKit. I can see the record in the CloudKit Dashboard, but am unable to get to it via code in app.

-(void)getUserRecordID {
    CKContainer *defaultContainer =[CKContainer defaultContainer];
    [defaultContainer fetchUserRecordIDWithCompletionHandler:^(CKRecordID *recordID, NSError *error) {
        if (!error) {

            [defaultContainer fetchUserRecordIDWithCompletionHandler:^(CKRecordID *recordID, NSError *error) {
                 self.userRecordID = recordID;
                NSLog(@"user record id: %@",recordID);
                [self getUserRecord];

            }];

       }
        else {
            NSLog(@"error: %@",error.localizedDescription);
        }
    }];

}

-(void)getUserRecord {
    CKContainer *defaultContainer =[CKContainer defaultContainer];   
    CKDatabase *publicDatabase = defaultContainer.publicCloudDatabase;
    [publicDatabase fetchRecordWithID:self.userRecordID completionHandler:^(CKRecord *userRecord, NSError *error) {
        if (!error) {
            NSLog(@"current coins: %@",userRecord);


        }
        else {
            NSLog(@"error: %@",error.localizedDescription);
        }
    }];
}

This gets me the User record information, but not the ID's of the saved private records. How can I get them?

Upvotes: 2

Views: 439

Answers (1)

WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

Figured out the solution. You have to query for private records using CKQuery and NSPredicate.

-(void)getUserRecordID {
    CKContainer *defaultContainer =[CKContainer defaultContainer];
    [defaultContainer fetchUserRecordIDWithCompletionHandler:^(CKRecordID *recordID, NSError *error) {
        if (!error) {
            self.userRecordID = recordID;
            NSLog(@"user record id: %@",recordID.recordName);
            [self getStatsRecord];
        }
        else {
            NSLog(@"error: %@",error.localizedDescription);
        }
    }];

}

-(void)getStatsRecord {
    CKDatabase *privateDatabase = [[CKContainer defaultContainer] privateCloudDatabase];
    CKReference *reference = [[CKReference alloc] initWithRecordID:self.userRecordID action:CKReferenceActionNone];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"creatorUserRecordID = %@", reference];
    CKQuery *query = [[CKQuery alloc] initWithRecordType:@"Stats" predicate:predicate];
    [privateDatabase performQuery:query inZoneWithID:nil completionHandler:^(NSArray *results, NSError *error) {
        if (error) {
            NSLog(@"error: %@",error.localizedDescription);
        }
        else {
            if (![results firstObject]) {
                [self createBlankRecord];
            }
            else {
                CKRecord *record = [results firstObject];
                NSLog(@"%@",record);
            }
        }
    }];

}

Upvotes: 1

Related Questions