0

I have been searching a while and I could not find a solution -> me opening a new thread.

I am making this register page which works with a token send to the users email, it has to be checked against the values in the database, however (in code below) it prints "false" before "hi", I have been trying to get it async, but it doesn't want to work. Can someone help me out? Thanks!

PS: The selection variable makes my app go to the next page in registration, which, because return is false, won't go to.

public static func tokenVerify(_ token: String) -> Bool{
    // Get database
    let db = Firestore.firestore()
    let collection = db.collection("tokens")
    let query = collection.whereField("token", isEqualTo: token)
    
    // Make response
    var response = false
    
    // Get all documents
    query.getDocuments { snapshot, error in            
        // Check for errors,
        if error == nil{
            // No error
            
            if let snapshot = snapshot {
                if snapshot.isEmpty {
                    print("No token in database")
                } else {
                    response = true
                    print("hi")
                }
            } else {
                print("Unknown Error")
            }
        } else {
            print("Error retrieving documents.")
        }
    }
    
    print(response)        
    return response
}

Main View:

DispatchQueue.main.async{
    if Registration.tokenVerify(token) {
        selection = "third"
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Daan Hermans
  • 31
  • 10
  • getDocuments Is asynchronous. You won’t be able to return directly from tokenVerify with a Bool. Look up “callback function” and “completion handler” or Swift’s new async/await. – jnpdx Feb 13 '22 at 14:52
  • Data is loaded from Firestore (and most modern cloud APIs) asynchronously. While that is going on, your main code continues to execute so the user can continue to use the app. Then when the data is available, the completion handler is called. The problem is that the `return response` in your code runs before the `response = true` every is executed. See the questions I linked for how to solve this with passing in a callback function/closure or a dispatch group. – Frank van Puffelen Feb 13 '22 at 15:40

0 Answers0