2016-09-26 29 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) 
}