I've been trying to retrieve some data from firebase and store it in arrays. But I've got a problem when I try to append the data.
I can store the data into arrays only in the closure and outside of the closure, i all the sudden lose all the values inside of the arrays. Why does this happen? Please help me to find what I'm missing...
var names = [String]()
var txts = [String]()
var imgUrls = [String]()
Database.database().reference().child("Posts").child("dummy").observe(.value) { (snapshot) in
guard let snapshots = snapshot.children.allObjects as? [DataSnapshot] else {
return
}
for snap in snapshots {
let autoId = snap.key as String
Database.database().reference().child("Posts").child("dummy").child(autoId).observe(.value, with: { (snapshot) in
guard let data = snapshot.value as? [String: Any] else {return}
//name
guard let name = data["name"] as? String else {return}
self.names.append(name)
//image
guard let imgUrl = data["image"] as? String else {return}
self.imgUrls.append(imgUrl)
//txt
guard let txt = data["text"] as? String else {return}
self.txts.append(txt)
print(self.names) //this returns all data from firebase
print(self.imgUrls) //this returns all data from firebase
print(self.txts) //this returns all data from firebase
}
print(self.names) //this returns empty array
print(self.imgUrls) //this returns empty array
print(self.txts) //this returns empty array
}
Could it be because you are assigning the data inside a closure which could happen in a later time. So basically the last print statement occurs before the closure statements.
I will recommend you use didSet to understand the sequence. For example:
var names: [String] = [String]() {
didSet {
print(names) // this is print each time the value is set
}
}
var txts: [String] = [String]() {
didSet {
print(txts)
}
}
var imgUrls: [String] = [String]() {
didSet {
print(imgUrls)
}
}
Database.database().reference().child("Posts").child("dummy").observe(.value) { (snapshot) in
guard let snapshots = snapshot.children.allObjects as? [DataSnapshot] else { return }
for snap in snapshots {
let autoId = snap.key as String
Database.database().reference().child("Posts").child("dummy").child(autoId).observe(.value, with: { (snapshot) in
guard let data = snapshot.value as? [String: Any] else {return}
//name
guard let name = data["name"] as? String else {return}
self.names.append(name)
//image
guard let imgUrl = data["image"] as? String else {return}
self.imgUrls.append(imgUrl)
//txt
guard let txt = data["text"] as? String else {return}
self.txts.append(txt)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.