1

I'm trying to get the current users first name from CloudKit using the following code:

func getUserFirstName() -> String{

    var firstNameFromFunction: String?
    var currentuserID : CKRecordID? 



    container.fetchUserRecordID(completionHandler: {
        userID, error in
        if ((error == nil)) {
            self.currentuserID = userID!

        }
    })

    container.discoverUserInfo(withUserRecordID: currentuserID!, completionHandler: {userInfo, error in

       let firstNameFromFunction = (userInfo!.displayContact?.givenName)!
    })
    return firstNameFromFunction!
}

However when executed, the currentUserID is nil, and creating the fatal error. Does anyone know why currentUserID is nil?

user4174219
  • 427
  • 5
  • 13

2 Answers2

0

Your App must successfully requestApplicationPermission for userDiscoverability before it can fetchUserRecordID.

San Lewy
  • 136
  • 1
  • 3
  • 13
0

The code to test if a value is nil looks like this. San maybe right with his answer; I would guess it may be nil too if the user isn't logged into his appleID on the device your running it on.

if self.currentuserID = userID {
// do something with self.currentuserID (the unwrapped value of userID)
} else {
// do something now that we know userID is nil
}
user3069232
  • 8,587
  • 7
  • 46
  • 87