我是 Firebase 的新手,我正在尝试构建一个应用程序,当用户启动该应用程序(有点像 Tinder)时,它会显示一个随机的用户配置文件。
经过几个小时的测试,我找到了一个可行的解决方案,但如果感觉不对!我在另一个观察者里面调用一个观察者,这样好吗?两个连接?不知道,但是感觉不好!但我找不到其他解决方案。
我的代码好还是不好?如果不正确,有人可以给我一些好的建议吗?
我的 firebase 数据库结构:
"profiles": {
"1": {
"name": "John Doe",
"age": "36",
"location": "Los Angeles",
"gender": "male",
},
"2": { ... },
"3": { ... }
},
我的 Swift IOS Firebase 代码
var profilesRef: DatabaseReference!
let profilesRef = Database.database().reference().child("profiles")
profilesRef.observe(.value, with: { (snapshot) in
let profilesCount = snapshot.childrenCount
let diceRoll : String = String(arc4random_uniform(UInt32(postsCount)))
profilesRef.child(diceRoll).observeSingleEvent(of: .value, with: { (snapshot) in
if let profileDict = snapshot.value {
let profile = Profile(profileData: profileDict as! Dictionary<String, AnyObject>)
print(profile.age)
}
})
})
它有效,但感觉不对。
最佳答案
无需再次从数据库中提取数据。您可以做的是获取从第一个快照收到的快照,将值存储在字典中,然后获取键“diceroll”的值。 您已经拉取过一次数据,无需再次拉取。
另外,附带说明一下,将个人资料存储在一个数字下并不是一个好的做法,因为如果有人删除了他们的个人资料,或者两个人同时创建了一个个人资料,数据就会出现差异。我建议查看“childByAutoID”,然后您可以通过将用户选择存储在数组中并选择随机索引来随机化用户选择。
如果您有任何问题,请告诉我!
关于ios - Firebase iOS swift : how to pick a random userProfile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194583/