我正在学习 Udemy 上的类(class),以使用 Firebase、Backendless 和 Swift 构建聊天应用程序。所有的问题(它是为 Swift 2 而不是 3 编写的)我已经能够自己解决,但是这个问题让我感到难过。这个函数应该从 Firebase 数据库中检索数据,显然它应该作为 NSArray 检索它,但它现在作为 NSDictionary 检索它,这在其他函数中产生了大量错误列表,因为它不期望词典。
func loadRecents() {
firebase.childByAppendingPath("Recent").queryOrderedByChild("userId").queryEqualToValue(currentUser.objectId).observeEventType(.Value, withBlock: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let sorted = (snapshot.value.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptior(key: "date", ascending: false)])
}
})
}
我已经更新到 Swift 3:
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! NSDictionary
}
})
}
当然是用as! NSArray
不起作用。如果有人可以建议一种方法来更新它以使用 Swift 3,按数据中的值对其进行排序,并能够在以后访问它,将不胜感激。谢谢!
最佳答案
func loadRecents() {
ref = FIRDatabase.database().reference()
let userId = currentUser?.getProperty("username") as! String
ref.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: userId).observe(.value, with: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let values = snapshot.value as! [String:AnyObject]
}
})}
或者你也可以使用 let values = snapshot.value as! [任何]
关于ios - 从 Firebase (Swift 3) 检索和读取数据作为 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477726/