Vishaal Kumar
Vishaal Kumar

Reputation: 25

Why does this loop execute before this piece of code?

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)
}  

Upvotes: 1

Views: 87

Answers (1)

Kerberos
Kerberos

Reputation: 4166

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.

Upvotes: 1

Related Questions