Danny Richard Aboo Danny Richard Aboo - 1 year ago 69
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 {
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 {
if results?.count == 1 {
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?


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download