0

I have a function bellow called retrieveUsers() which is called inside a function which fetches all posts under a Post node.

Inside the code found bellow I save the current UID to a variable with global scope. But every time this function gets called the variable (lastUID) seems to be reset. Even though this method is being called in a for-loop essentially.

 func retrieveUsers(value: Post) {
    print(lastUID, "-=-=--=-=")
    print(value.user.userID != lastUID, ": ", value.user.userID!, " email left old ... one -> ", lastUID)

    if value.user.userID != lastUID {//Ignore this line
        let ref = Database.database().reference()
        if value.user.userID != nil {
            let UID = value.user.userID!
            print(UID, "Thoi s is the uid in the users fetch fx")
            ref.child("users2").child(UID).observe(.value, with: { (snapshot) in
                let email = "\(snapshot.childSnapshot(forPath: "email").value as! String)"
                do {
                    value.user.email = email
                    //even with the two values being in here the same thing happens
                }
                self.lastUID = UID
                self.lastEmail = email
            })
        }
    } else {
        print("ESC this is the same user")
        value.user.email = lastEmail
    }
}

What is going wrong?

  • 1
    Data is loaded from Firebase asynchronously. You need to make sure that all code that needs the data is inside the closure (or called from there). See https://stackoverflow.com/questions/43823808/access-firebase-variable-outside-closure, https://firebase.googleblog.com/2018/07/swift-closures-and-firebase-handling.html, https://stackoverflow.com/questions/40904141/access-data-outside-of-closure-firebase-observesingleevent-swift/40952103#40952103 – Frank van Puffelen Mar 02 '19 at 21:44

1 Answers1

0

Even though this method is being called in a for-loop essentially.

The global var is changed every cycle of the for - loop and since the calls to firebase are asynchronous , hence you can't catch every fetch with it's corressponding UID

You need to create a model and make those calls inside it with a property as the uid

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • So you are saying that the value can only exist if inside the closure or if saved to a object which can store the value? So despite it being saved to the gloabal variable, for some reason the code will not keep the value i storage? –  Mar 02 '19 at 21:50
  • yes ,,,,,, the for loop overrides the value before your response returns from firebase – Shehata Gamal Mar 02 '19 at 21:51