Как Swift сортирует данные из Firebase? - PullRequest
0 голосов
/ 22 ноября 2018

У меня есть эта структура в Firebase:

"OpeHS4UhH6YWcK4aPHJWumueCQP2" : {
      "Orders" : {
        "Date" : {
          "-LRw0wJMtbYQmy34F3SS" : 1542900401608,
          "-LRw1-MpaWeQkCxkV08_" : 1542900418212,
          "-LRw11xb7PhD-iYPTz8P" : 1542900428823,
          "-LRw13xl0p3gxOIsmKdI" : 1542900437024
        },
        "Order" : {
          "-LRw0wJMtbYQmy34F3SR" : "1 Orange ",
          "-LRw1-Mo8sXFCugSzSuN" : "2 Banana ",
          "-LRw11xb7PhD-iYPTz8O" : "3 Apple ",
          "-LRw13xkb9z5TsCg5eUq" : "4 Tomato "
        }
      }
    }    

1 Оранжевый пишется первым, 2 банановых секунды и так далее.Данные в идеальном порядке в Firebase.
Точно так же отметка времени в разделе Date записывается в том же порядке.
Но когда я читаю ее из Firebase и помещаю в tableView, отметка временив порядке, самый старый внизу и самый новый сверху.Но раздел Order вроде бы добавляется случайным образом?
Screenshot of tableView

Данные читаются так:

class OrderHistoryTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var orderDateHistoryArray = [Any]()
    var orderItemsHistoryArray = [String]()


    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        tableView.estimatedRowHeight = 80
        tableView.rowHeight = UITableView.automaticDimension
    }

    override func viewDidAppear(_ animated: Bool) {
        getOrderHistory()
        getOrderDates()
    }


     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return orderItemsHistoryArray.count

    }



     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderHistoryCell") as! OrderHistoryTableViewCell

        cell.orderHistoryItemsLabel.text = orderItemsHistoryArray[indexPath.row]
        cell.orderHistoryDateLabel.text = "\(orderDateHistoryArray[indexPath.row])"

        return cell

    }


    func getOrderHistory() {
        //Get userinfo from database

        let uid = Auth.auth().currentUser!.uid
        let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")

        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in

            let value = snapshot.value as? NSDictionary
            if  let orderItem = value?["Order"] as? [String:String] {
                self.orderItemsHistoryArray += Array(orderItem.values)
                //print(orderItem)
            }
            self.tableView.reloadData()

            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
    }

    func getOrderDates() {

        let uid = Auth.auth().currentUser!.uid
        let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")

        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in

            let value = snapshot.value as? NSDictionary
            if  let orderDate = value?["Date"] as? [String:Int] {

                let dates = orderDate.values.map {Date(timeIntervalSince1970: TimeInterval ($0/1000)) }
                let formatter = DateFormatter()
                formatter.calendar = Calendar(identifier: .iso8601)
                formatter.locale = Locale(identifier: "nb_NO")
                formatter.timeZone = TimeZone(secondsFromGMT: 0)
                formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
                let readableDates = dates.map {formatter.string(from: $0)}
                self.orderDateHistoryArray = readableDates

                print(dates)
            }
            self.tableView.reloadData()
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...