2017-08-28 112 views
1

这是我的数据结构:很多俱乐部,每个俱乐部都有地址。我试图让数据库保持平坦。如何阅读firebase数据库

现在我想在表格视图中加载一些俱乐部信息。当我向下滑动iPhone屏幕时,它会加载下一个俱乐部信息。

enter image description here

这是我的代码。但它会加载所有俱乐部信息。我怎样才能加载一些俱乐部,并在用户向下滑动时加载下一个俱乐部?

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) 
        } 
       } 
      } 
     }) 

    } 

回答

0

我认为正确的方式提及元素, 的阵列中,并使变量指数

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 

所以在你的例子是这样的:

func loadClubs(index, forward) { 

    ref = Database.database().reference() 

    ref.child("club").observe(data => { 
     var club = data[index]; 
     if(forward){ 
     index ++ 
     }else{ 
     index-- 
     } 
    return club; 
    })  
} 
3

火力地堡的查询支持分页,但与您以前的习惯略有不同。 Firebase不使用偏移量,而是使用所谓的锚值来确定从何处开始。

获取项目的第一页是容易的,你只需指定一个限制项目的数量来获取:

ref = Database.database().reference() 
    query = ref.child("club").queryOrderedByKey().limitToFirst(10) 

    query.observe(DataEventType.value, with: { (snapshot) in 

现在块内,保留最后一个项目你”的关键的轨迹VE显示给用户:

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) 
      } 
     } 
    } 

然后获取下一个页面,构建开始于你见过的最后一个键查询:

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

由于在两个页面都检索了锚点项目,因此您需要检索一个多于页面大小的项目。