SwiftER
SwiftER

Reputation: 1255

How to reverse order of items from Firebase

How can I reverse the order of this list in from Firebase? I want the last item to be the first. I tried to use queryOrdered, but that did not make a difference. I listed one sample of the data structure that I'm retrieving from Firebase:

"-KhPRPQEOiVzPW7G2iQI" : {
            "amount" : "20",
            "coordinate" : {
              "lat" : 28.10388759332169,
              "long" : -81.46038228976457
            },
            "creationTime" : "2017-04-11 00:37:29 +0000",
            "creator" : "6MAK7nkzoBT6NzIxj7DW3564cf72",
            "description" : "A ride ",
            "distanceRadius" : 1609.34,
            "expireTime" : "2017-04-11 03:37:00 +0000",
            "paymentNonce" : "51df2b01-9e97-0fce-14d5-fc8fdf98603c",
            "provider" : "PSEFUZdAAxRH14oYnyzE7yMpcil1",
            "status" : "accepted"
          },

Code:

func retrieveRquestFromFir(){
        var searchType:String!
        switch self.messageType {
        case messageTypeEnum.creator:
            searchType = "creator"
            break
        case messageTypeEnum.provider:
            searchType = "provider"
            break
        }
        //TODO: Fix here
        let path = "rquest/frontEnd/posts/userCreatedPost"
        self.childRef(path).queryOrdered(byChild: "creationTime") .observe(.childAdded, with: {snapshot in
            if let snapDict = snapshot.value as? NSDictionary {
                if let postId = snapDict[searchType] as? String {
                    if  postId == self.currentUserId()! {
                        let rquestId = snapshot.key
                        let status = snapDict["status"] as! String
                        //check to see if message is pending or accepted in order to show messages
                        if status == "pending" || status == "accepted" {
                            let description = snapDict["description"] as! String
                            let amount = snapDict["amount"] as! String
                            let creator = snapDict["creator"] as! String
                            var provider:String?
                            // calculate expire time here
                            var expireTime:String!
                            let dateString = snapDict["expireTime"] as! String
                            var date:Date!
                            if status == "pending" {

                                 date = Date(string: dateString, format: "yyyy-MM-dd HH:mm:ss Z")!
                                if date < Date() {
                                    return
                                }
                            }else if status == "accepted" {
                                expireTime = snapDict["expireTime"] as! String
                                date = Date(string: dateString, format: "yyyy-MM-dd HH:mm:ss Z")!
                            }
                            if let providerUser = snapDict["provider"] as? String {
                                provider = providerUser
                            }
                            let array = [
                                "expireTime":dateString,
                                "amount":amount,
                                "description":description,
                                "rquestId":rquestId,
                                "status": status,
                                "provider":provider as Any,
                                "creator": creator
                                ] as NSDictionary
                            //check if date is more than 5 days if it is more than dont Added
                            let dateAmount = Date.daysBetween(start: date, end: Date())
                            // let StringDate = newDate?.string(withFormat: "yyyy-MM-dd HH:mm:ss Z")

                            if dateAmount <= 5 {
                                DispatchQueue.main.async {
                                    self.RquestInfoArray.append(array)

                                    self.tableView.reloadData()
                                }
                            }
                        }
                    }
                }else {
                    DispatchQueue.main.async {
                       self.RquestInfoArray.append(array)
                        self.tableView.reloadData()
                    }
                }
            }
        })
    }

Upvotes: 1

Views: 1821

Answers (2)

Bogdan Oloeriu
Bogdan Oloeriu

Reputation: 327

One trick that I'm using is to add a field to my object that stores the time-stamp as reversed value. The value of this field I compute when I persist the object and is reversedDateCreated = timeStamp * -1 Now you can use default Firebase orderBy methods in order to sort and paginate by reversedDateCreated field

Upvotes: 2

Russell
Russell

Reputation: 5554

As @Frank says, you need to sort your results client-side.

You can either sort the array with something like this

let sorted = self.RquestInfoArray.sorted(by: { (r1: RequestInfoType, r2: RequestInfoType) -> Bool in
            return r1.dateAmount > r2.dateAmount
})

but if you really just want to reverse the array, probably simpler just to add your new elements at the start instead of the end

self.RquestInfoArray.insert(contentsOf: array, at: 0)

Upvotes: 1

Related Questions