0

I currently have a button that when pressed checks if a function returns a true or false parameter. The function in question checks a code in a database and returns true if it is there, and false if it is not. However, the function returns false by default as it takes a second for the database to return a response. Is there any way for me to get the function to wait for the response to come in before returning a response to the if statement in question? That way when the button is pressed and the if statement runs which checks if the function result is true or false, it gets an accurate response? Enclosed is the if statement itself, as well as the function.

 if ps.getNEWStatus(name: partnerCodeField.text!) == true {
                partnerCode = partnerCodeField.text!
                ps.getStatus()
                
            } else if ps.getNEWStatus(name: partnerCodeField.text!) == false {
                holdText.text = "Partner code is invalid."
                
            }

Function

     func getNEWStatus(name: String) -> Bool {
        
        db.collection("users").document(name)
.addSnapshotListener { documentSnapshot, error in
              guard let document = documentSnapshot else {
              //  print("Error fetching partner status: \(error!)")
                return
              }
              guard let data = document.data() else {
              //  print("No partner with this code exists.")
                isPartnerValid = false
                return
              }
                if let isOnline = data["isOnline"] as? Int {
                    isPartnerValid = true
                    
                }
            }
        
        if isPartnerValid == true {
        return true
        } else if isPartnerValid == false {
            return false
        }
        return false
    }
  • 1
    Possible duplicate of: [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – TylerP Sep 12 '20 at 04:22

1 Answers1

0

What you are looking for is an asynchronous function, these functions wait for a specific operation to be done before continuing, just like a db read, after the db.read is finished you can use a completionHandler() to verify the result

Here's more info on asynchronous operations: https://developer.apple.com/documentation/foundation/nsoperation#1661231

Alexis
  • 71
  • 4