我正在尝试从数据库中检索数据,但是遇到一些问题,这是我的数据库结构:
这是我的代码
var ref : DatabaseReference
var idString = [String]()
ref = Database.database().reference()
ref.child("idUsers").observe(.value){ (snapshot) in
let id = snapshot.value as? String
if let ids = id {
idString.append(ids)
print(ids)
}
}
但是没有数据进入我的阵列,我一直在尝试一些解决方案,但是没有人可以解决,请帮忙!顺便说一下,这些是我的规则,默认情况下是公开的。
{
"rules": {
".read": true,
".write": true
}
}
答案 0 :(得分:0)
由于idUsers
包含多个子节点,因此需要遍历代码中的结果。像这样:
ref.child("idUsers").observe(.value){ (snapshot) in
for userSnapshot in in snapshot.children.allObjects as? [DataSnapshot] {
let id = userSnapshot.value as? String
print(id)
idString.append(id)
}
print(ids)
}
答案 1 :(得分:0)
**For creating database structure**
`override func viewDidLoad() {
var ref: DatabaseReference!
ref = Database.database().reference()
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
Auth.auth().signIn(withEmail: email, password: password) { [weak self] user, error in
guard self != nil else { return }
ref.child("users").setValue(["test1": "abc",
"test2": "efg",
"test3": "hij"])
}
}
}`
**// For retrieving data from firebase**
ref.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
for item in postDict {
print(item)
}
})