我试图将所有用户提取到一个数组中,并在完成后使用回调。我需要知道何时完成提取。我已经了解到,这可能无法按照我对childAdded的想法进行工作,因此我正在尝试使用observeSingleEvent,但是我在提取数组时遇到了问题。有什么想法吗?
这个带有childAdded的代码可以将数据放入数组中,即使我将其放入数组中也不能完成。
self.ref?.child("Users").observe(DataEventType.childAdded, with: { (snapshot) in
// Fetch users
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String
let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key
})
self.usersArray.append(user)
}
})
//dump(self.usersArray)
completion("FetchAllUsersKlar")
此代码根本不起作用:
self.ref?.child("Users").observeSingleEvent(of: .value, with: { (DataSnapshot) in
// Fetch users
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.nameLabel = dictionary["Username"] as? String
user.occupationLocation = dictionary["Occupation"] as? String
user.ageLabel = dictionary["Age"] as? String
user.infoText = dictionary["Bio"] as? String
user.emailText = dictionary["email"] as? String
let email = user.emailText
let ref = Database.database().reference().child("Users")
ref.queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
user.toId = snapshot.key
})
self.usersArray.append(user)
}
completion("FetchAllUsersKlar")
})
Firebase看起来像这样:
答案 0 :(得分:2)
这是用户结构:
struct User{
var id:String
var username:String?
var occupation:String?
var age:Int?
var bio:String?
var email:String?
}
这是firebase查询,尽管我认为通过Codable解码对象要好得多,但是为了坚持您的示例,我使用键解析了对象。
let query = self.ref.child("Users").queryOrdered(byChild: "email")
query.observeSingleEvent(of: .value) {
(snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
let id = child.key
let value = child.value as? NSDictionary
let username = value?["Username"] as? String
let occupation = value?["Occupation"] as? String
let age = value?["Age"] as? Int
let bio = value?["Bio"] as? String
let email = value?["email"] as? String
let user = User(id: id, username: username, occupation: occupation, age: age, bio: bio, email: email)
self.usersArray.append(user)
}
completion("Users list fetched")
}