How to read firebase database

This is my data structure: a lot of clubs, every club has an address. I tried to make the database flat.

Now I want to download some information about the club in a table. When I scroll the iPhone screen, it will download the following club information.

enter image description here

This is my code. But he downloads all the information about the club. How can I load only a few clubs and load the next few clubs when a user sits down?

func loadClubs() { ref = Database.database().reference() ref.child("club").observe(DataEventType.value, with: { (snapshot) in //print("clubs: \(snapshot)") let array:NSArray = snapshot.children.allObjects as NSArray for obj in array { let snapshot:DataSnapshot = obj as! DataSnapshot if let childSnapshot = snapshot.value as? [String: AnyObject] { if let clubName = childSnapshot["name"] as? String { print(clubName) } } } }) } 
+1
source share
2 answers

Firebase queries support pagination, but are slightly different from what you're used to. Instead of working with offsets, Firebase uses what are called snap values ​​to determine where to start.

Getting elements for the first page is easy, you just specify a limit on the number of elements to retrieve:

  ref = Database.database().reference() query = ref.child("club").queryOrderedByKey().limitToFirst(10) query.observe(DataEventType.value, with: { (snapshot) in 

Now in the block, track the key of the last element that you specified to the user:

  for obj in array { let snapshot:DataSnapshot = obj as! DataSnapshot if let childSnapshot = snapshot.value as? [String: AnyObject] { lastKey = childSnapshot.key if let clubName = childSnapshot["name"] as? String { print(clubName) } } } 

Then, to get the next page, create a query that starts with the last key you saw:

  query = ref.child("club").queryOrderedByKey().startAt(lastKey).limitToFirst(11) 

You will need to extract another element than the size of your page, since the anchor element is extracted on both pages.

+3
source

I think the correct path refers to an array of elements, and make a variable for the index

 var i = 0; var club = null; club = loadClubs(index); // here should return club with specified index; // and increment index in loadClubs func, // also if you need steped back --- and one more // argument to function, for example // loadClubs(index, forward) // where forward is // boolean that says in which way we should // increment or decrement our index 

so in your example there will be something like this:

 func loadClubs(index, forward) { ref = Database.database().reference() ref.child("club").observe(data => { var club = data[index]; if(forward){ index ++ }else{ index-- } return club; }) } 
0
source

Source: https://habr.com/ru/post/1271869/


All Articles