Danny Richard Aboo Danny Richard Aboo - 13 days ago 6
Swift Question

Check existance of record with a specified value in CloudKit using swift

I have a problem. I am doing an app that has login capabilities and would like to check if a user with a specified username exists. So I did:

func doesRecordExist(inRecordType: String, withField: String, equalTo: String) -> Bool {
print(withField,equalTo)
var result = false

let predicate = NSPredicate(format: "\(withField) == %@", equalTo)
let query = CKQuery(recordType: inRecordType, predicate: predicate)
publicDatabase.perform(query, inZoneWith: nil, completionHandler: {results, er in

if results != nil {
print(results!.count)
if results?.count == 1 {
print(results!.count)
result = true
}
}
})
return result
}


where in withField "username" will be entered and in equalTo the value will be entered which is the username.

What did I do wrong?
Thanks.

Edit

Ok, I've finally figured out how to do what rmaddy suggesteed and it worked. Thanks you very much!

Answer

You can't return a value from a function if that function's result depends on the result of an asynchronous action. As written, the return result line at the end of the function (with a value of false) will be called long before the database query is even started.

Your doesRecordExist function needs to use a completion handler parameter much line the perform function does.

Of course you will need to refactor your code that calls your doesRecordExist to deal with the fact that you will not get back an immediate result.

Comments