Extremely confused by the scope of Firestore GetDocuments request and the in loop of Swift

Viewed 473

All that I'm trying to do is to check whether the value for a 'key' exists in a Firestore collection as a document and return a Bool.

But I can't seem to return anything within the getDocument, so I thought that I should then keep a results var and update the results var but the changes I make to results don't stick and it stays default false.

How do I simplify this whole mess?

 func checkIfValid(db: Firestore, key: String) -> Bool {


    let resolve = db.collection("keys").document(key)

    var results = false

    resolve.getDocument{ (document, error) in

        if let document = document, document.exists {

            var results = true
        } else { results = false }
    }
    print(results)

    return results
}
1 Answers

Reading the firebase docs, they have a small warning below the sample code.

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

However, you need to add a completion handler to the function given you're working with network requests. Swift will return the result variable given you specified it; ignoring any response from the getDocuments handler.

I changed the function to fix your mess.

func checkIfValid(db: Firestore, key: String, completion: @escaping(Bool) -> ()) {
let docRef = db.collection("user").document(key)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        print("document exists.")
        completion(true)
    } else {
        print("document does not exists.")
        completion(false)
    }
}
}

And to get the response, just use this.

checkIfValid(db: db, key: "", completion: {success in
   print(success)
})
Related