Asynchronous functions and Firebase with Swift 3

I read some questions about that. But I still have issues with asynchronous functions.

For example: I have a viewController1 where a button perform a segue to a viewController2. In the viewController2 class, I initialize some values in another class file named exampleClass. These values are retrieved from Firebase database or location values. These values need a little moment to be retrieved. I return thes values from the exampleClass into my viewController2. I print these values in the viewController2 viewDidLoad().

My issue: The device doesn't wait that the values are retrieved and execute following functions. Result: When I touch the button, printed values are nil values. It can also make the app crash if I don't secure the code.

What I've found so far: I learned that I only have to call a func at the end of a Firebase snapshot (for example) like this:

    userRef.observeSingleEvent(of: .value, with: { (snapshot) -> Void in
        self.name = snapshot.value as! String!
        print(self.name)
        self.forceEnd()
    }) { (error) in
        print(error.localizedDescription)
    }

I named this function forceEnd to be clear. This is not working for me. I also tried to create handlers but no positive results.

My question: How can I force the device to wait for the values to be retrieved before performing the following question?

Upvotes: 0

Views: 968

Answers (1)

ystack
ystack

Reputation: 1805

How can I force the device to wait for the values to be retrieved before performing the following question?

  • You don't want to force the device to wait, only need to perform some operations once these values are retrieved from Firebase database.
  • Performing an operation asynchronously can be done in multiple ways like blocks, protocols, notifications, etc.

Generally, blocks are the more elegant approach.
Some sample code can be like:

func myFirebaseNetworkDataRequest(finished: () -> Void) { // the function thats going to take a little moment

     ...

     print("Doing something!") // firebase network request

     finished()    
}


// usage of above function can be as-

override func viewDidLoad() {

     myFirebaseNetworkDataRequest {

          // perform further operations here after data is fetched
          print("Finally! It took a lot of moments to end but now I can do something else.")
     }
}

Upvotes: 1

Related Questions