Search code examples
ioscloudkit

How to set the reference to the current user, in CloudKit?


I have a CKRecordType with a reference field that I want to set to the current user of the app. enter image description here

CKRecord * record = [[CKRecord alloc] initWithRecordType:@"UserStatus"];
[record setValue:@"online" forKey:@"status"];
// what user should be?
[record setValue:user forKey:@"user"];

How should I do that?


Solution

  • First, get the userId:

    - (void)getUserId
    {
        [self.defaultContainer fetchUserRecordIDWithCompletionHandler:^(CKRecordID * _Nullable recordID,
                                                                        NSError * _Nullable error)
         {
             if (error == nil)
             {
                 self.userRecordID = recordID;
             }
         }];
    }
    

    Then:

    CKRecord * record = [[CKRecord alloc] initWithRecordType:@"UserStatus"];
    record[@"status"] = @"online";
    
    CKReference *userReference = [[CKReference alloc] initWithRecordID:self.userRecordID action:CKReferenceActionDeleteSelf];
    record[@"user"] = userReference;