Swift 3 Firebase update code convertion - sorting

╄→гoц情女王★ 提交于 2019-12-25 07:25:29

问题


I enrolled a course on Udemy a while back, on how to create a chat application with Swift and Firebase, simply because I wanted to get an insight of how it all was working.

However, I finished the course a week later. This was a couple of months ago, and since then - there has been an update to both Firebase and Swift, and I am currently struggling with converting some of the old code, to new code.

Here is the code that I am currently struggling with:

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

    }

So this is simply the code of displaying all the "Chats" in a tableView, where I am simply sorting it through Date, where ascending is false.

The changes that I have made, is simply to convert the old snapshot.value.allValues to snapshot.value as? [String:AnyObject]. The query is sorted by the logged in account (FIRAuth.auth().currentUser!.uid).

However, I am very sure this code is deprecated, as I get an error each time I build this. And I know for a fact that it worked in the previous version.

This is the error:

Thread 1: EXC_BAD_INSTRUCTION

And if it is necessary, and it happens that I have messed up the current code completely (which might be), here is the full old code:

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

    }

Any ideas on how I would bypass/fix this? Help is greatly appreciated.


回答1:


You have to use Dictionary()

if let values = (snapshot.value) as! Dictionary




回答2:


I don't know the Firebase structure but here's a solution if the data looks like this:

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

and some code to print the data sorted by the date (this would go inside the block/closure)

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


来源:https://stackoverflow.com/questions/39705363/swift-3-firebase-update-code-convertion-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!