Swift 3 Firebase更新代码转换 – sorting

我之前在Udemy注册过一门课程,关于如何使用Swift和Firebase创build一个聊天应用程序,仅仅是因为我想了解一切是如何工作的。

不过,我一周后完成了课程。 这是几个月前,从那以后 – 对Firebase和Swift进行了更新,目前我正在努力将一些旧代码转换为新代码。

这是我目前正在努力的代码:

func loadRecents() { firebase.child("Recent").queryOrdered(byChild: "userId").queryEqual(toValue: FIRAuth.auth()!.currentUser?.uid).observe(.value) { (snapshot:FIRDataSnapshot) in self.recents.removeAll() if snapshot.exists() { if let values = snapshot.value as? [String:AnyObject] { let sorted = (values as! NSArray).sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)]) for recent in sorted { self.recents.append(recent as! NSDictionary) self.conversationTableView.reloadData() } } self.conversationTableView.reloadData() } self.conversationTableView.reloadData() } self.checkUnread() } 

所以这只是在tableView中显示所有“聊天”的代码,我只是通过Date对其进行sorting,其中升序是错误的。

我所做的更改仅仅是将旧的snapshot.value.allValues转换为snapshot.value as? [String:AnyObject] snapshot.value as? [String:AnyObject] 。 查询按已login帐户(FIRAuth.auth().currentUser!.uid)sorting。

不过,我非常肯定这个代码已经被弃用了,因为每次构build这个时都会出错。 而且我知道它在以前的版本中有效。

这是错误的:

 Thread 1: EXC_BAD_INSTRUCTION 

如果有必要的话,我发现现在的代码已经搞乱了(可能是),下面是完整的旧代码:

  func loadRecents() { firebase.child("Recent").queryOrderedByChild("userId").queryEqualToValue(FIRAuth.auth()!.currentUser!.uid).observeEventType(.Value, withBlock: { snapshot in self.recents.removeAll() if snapshot.exists() { let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date", ascending: false)]) for recent in sorted { self.recents.append(recent as! NSDictionary) //add functio to have offline access as well, this will download with user recent as well so that we will not create it again firebase.child("Recent").queryOrderedByChild("chatRoomID").queryEqualToValue(recent["chatRoomID"]).observeEventType(.Value, withBlock: { snapshot in }) } } self.tableView.reloadData() }) self.checkUnread() } 

任何想法,我将如何绕过/解决这个问题? 非常感谢帮助。

你必须使用Dictionary()

如果让值=(snapshot.value)为! 字典

我不知道Firebase结构,但是如果数据如下所示,这里有一个解决scheme:

 [ ("post_42", ["date": "2016-09-16"]), ("post_12", ["date": "2016-09-19"]), ("post_87", ["date": "2016-09-04"]) ] 

和一些代码来打印按datesorting的数据(这将进入块/closures)

 let dict = snapshot!.value as! [String:[String:String]] //print the unordered data from the dictionary for item in dict { print(item) } let sortedArray = Array(dict).sorted { $0.1["date"]! < $1.1["date"]! } //print the data sorted by date for sortedItem in sortedArray { print(sortedItem) }