为什么即使在firebase代码之后键入for循环,也要在firebase代码之前执行for循环?
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)
}
答案 0 :(得分:1)
这是因为firebase observe
事件是asynchronous,因此,如果要在此之后执行代码,则需要将其移入块中。
所以您的代码将是:
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 }
或在单独的方法(如注释的代码)中调用它。
在关闭ViewController时,请不要忘记remove观察。