Pulling Data From Firebase Issue

后端 未结 3 1150
孤街浪徒
孤街浪徒 2021-01-25 00:51

Novice programmer, currently working on an ios app using firebase as our backend. I\'m trying to grab values from the firebase database to populate a TableView, but there are tw

3条回答
  •  有刺的猬
    2021-01-25 01:25

    Firebase is asynchronous: it takes time for values to be returned from Firebase via a query or observe call.

    Your code isn't allowing for that so whats happening is the observeSingleEvent is called and the cellForRowAt function is returning (an empty) cell before Firebase has a chance to return the data and populate committee.

    Code is way faster than the internet so you need to operate on data within the observe blocks (closures) as that's the time when it's valid.

    Best practice is to populate the datasource within an Firebase observe block (closure) - here are the steps

    1. Get the values from Firebase via observe .value block
    2. Within the block, iterate over the returned values and populate an array (datasource)
    3. Reload the tableView

    and to sort by Head Char, here's a swifty solution. Assume the dict is populated with .values from Firebase

    let dict = ["0": ["name": "First Disarmament and International Security Committee",
                  "Head Chair": "Jessie Mao"],
                "1": ["name": "UN Special,  Political And Decolonization Committee",
                  "Head Chair": "Trevor Dowds"],
                "2": ["name": "UN 6th Legal Committee",
                  "Head Chair": "Benjy Malings"]
    ]
    let sortedArray = Array(dict).sorted { $0.1["Head Chair"]! < $1.1["Head Chair"]! }
    

提交回复
热议问题