Search code examples
iosswifticloudcloudkitcompletionhandler

CloudKit fetchUserRecordIDWithCompletionHandler completion code not calling?


I am trying to fetch the current user ID from CloudKit using fetchUserRecordIDWithCompletionHandler but when I run the code, the completion handler is skipped over.

let container = CKContainer.defaultContainer()
let publicDatabase = container.publicCloudDatabase

var userID: CKRecordID!

container.fetchUserRecordIDWithCompletionHandler( { recordID, error in
    if error == nil {
        userID = recordID

    } else {
        NSLog("\(error.localizedDescription)")
    }
})


let predicate = NSPredicate(format: "personID = \(userID)")

let query = CKQuery(recordType: "Person", predicate: predicate)

Because of this, the value of userID stays nil, and so the query throws an exception because of it.


Solution

  • The completion handler will only run once the fetch request is complete, which will happen asynchronously. So you cannot use the result of the fetch request immediately after the call. Move that query into the completion handler of to some other part of your code that can be called or otherwise triggered from the handler.