2016-09-26 30 views
0

我之前在Udemy上注册了一门课程,关于如何使用Swift和Firebase创建聊天应用程序,仅仅是因为我想了解它是如何工作的。Swift 3 Firebase更新代码转换 - 排序

但是,我在一周后完成了课程。这是几个月前的事情,从那以后 - 对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,在那里我只是通过日期,在上升排序它显示所有的“聊天”的代码是错误的。

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

但是,我非常确定此代码已被弃用,因为每次构建时都会出现错误。我知道它在以前的版本中有效。

这是错误:

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() 

    } 

关于如何绕过/解决这个问题的任何想法?非常感谢帮助。

回答

0

您必须使用字典()

if let values =(snapshot.value)as!字典

+0

奇怪的是,这似乎并没有解决问题。嗯.. – askaale

0

我不知道火力地堡结构,但如果数据看起来像这样在这里是一个解决方案:

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

和一些代码来打印的日期排序的数据(这将去块内/关闭)

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) 
}