1

Why does the for loop execute before the firebase code even though it is typed in after the firebase code?

messageDB.observe(.childAdded) { (snapshot) in
    let snapshotValue = snapshot.value as! Dictionary<String,String>
    print("Snapshot value \(snapshotValue)")
    let email = snapshotValue["UserEmail"]!
    if (email == Auth.auth().currentUser?.email as String?){
        let user : UserString = UserString()
        user.name = snapshotValue["UserName"]!
        user.height = snapshotValue["UserHeight"]!
        user.weight = snapshotValue["UserWeight"]!
        user.date = snapshotValue["EntryDate"]!
        userArray.append(user)
    }    
}

for index in 0...4{
    print(index)
}  
Kerberos
  • 4,036
  • 3
  • 36
  • 55
  • 2
    Because `observe` works asynchronously. – vadian Aug 01 '19 at 07:12
  • 1
    Firstly read [here](https://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean). Then the observe works async so if you want that the loop is executed after the observe you need to add it into the block. – Kerberos Aug 01 '19 at 07:14
  • @Kerberos Thank you! Sorry but I'm really new to iOS development. How can I add the loop into the block so its executed after? – Vishaal Kumar Aug 01 '19 at 07:26
  • 1
    @VishaalKumar I added an answer because it did not fit into the comment. – Kerberos Aug 01 '19 at 09:29

1 Answers1

1

This is because the firebase observe event is asynchronous, so if you want to execute a code after this you need to move it into the block.

So your code will be:

messageDB.observe(.childAdded) { (snapshot) in
        let snapshotValue = snapshot.value as! Dictionary<String,String>
        print("Snapshot value \(snapshotValue)")
        let email = snapshotValue["UserEmail"]!
        if (email == Auth.auth().currentUser?.email as String?){
            let user : UserString = UserString()
            user.name = snapshotValue["UserName"]!
            user.height = snapshotValue["UserHeight"]!
            user.weight = snapshotValue["UserWeight"]!
            user.date = snapshotValue["EntryDate"]!
            userArray.append(user)
        }
        for index in 0...4{
           print(index)
        }
        // self.afterBlock()
    }

// func afterBlock() { yourCodeHere }

Or call it in a separate method like in the commented code.

Not forget to remove the observe when you dismiss your ViewController.

Kerberos
  • 4,036
  • 3
  • 36
  • 55