Tyler Rutt
Tyler Rutt

Reputation: 597

Retrieve certain amount of children from Firebase

I am trying to create a tableView that loads only a certain amount of values, let's say like 30 or so from my database.

I've looked at other tutorials for this, but they are in Objective-C or some other language. Swift would be great!

Upvotes: 1

Views: 918

Answers (2)

Lepidopteron
Lepidopteron

Reputation: 6165

For Reference to the FireBase Documentation see: https://www.firebase.com/docs/ios/guide/retrieving-data.html#section-queries

There is Objective-C and Swift Code referenced.

In short: you can make use of two functions:

open func queryLimitedToLast(limit: UInt) -> FIRDatabaseQuery
open func queryLimitedToFirst(limit: UInt) -> FIRDatabaseQuery

UInt is a data type "unsigned int". Means: pass a positive number to the function :-)

Don't forget, to observe the results of the query by calling the "observeEventType" on it - this function contains a block, in which you can make use of your items (e.g. you could add them to an array of items. The array could be used for your tableview's datasource. Finally, reload the tableview

An Example to call it, could look like this (for your 30 entries) (e.g. in your viewDidLoad):

DataSource Array Declaration as Class Variable

var objects = [MyObjects]()

Perform your Query:

override func viewDidLoad() {
    super.viewDidLoad()

    let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
    ref.queryLimitedToLast(30)
       .observeEventType(.ChildAdded, withBlock: { snapshot in
        println(snapshot.key)
        var newItems: [MyObject] = []
        for item in snapshot.children {
            let myObject = MyObject(snapshot: item as! FIRDataSnapshot)
            newItems.append(myObject)
        }
        self.objects = newItems
        self.tableView.reloadData()
    })
}

And the interesting table view DataSource method could look like this:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

Upvotes: 2

Paulo Mattos
Paulo Mattos

Reputation: 19339

Swift. Get a FIRDatabaseReference to the parent node and then run a query using this function:

func queryLimited(toFirst limit: UInt) -> FIRDatabaseQuery

And then retrieve the resulting children using:

func observeSingleEvent(of eventType: FIRDataEventType, with block: @escaping (FIRDataSnapshot) -> Void)

Upvotes: 3

Related Questions