2017-10-28 134 views
2

我想解决的问题是,我想用两个节点上的匹配信息来填充集合视图单元,并且需要在“播放器”节点中多次读取。Swift Firebase从多个节点读取

这里是我的火力地堡数据库结构

{ 
    Players: 
     LpWgezRkC6EWS0sjXEWxhFl2: { 
      userName: 'John Doe' 
      teamId: '234' 
      teamName: 'Revenge' 
      teamLogo: 'star.png' 
      etc... 
     }, 
     RfskjEWSkdsjkjdskjsd12fg: { 
      userName: 'Jane Doe' 
      teamId: '987' 
      teamName: 'Frills' 
      teamLogo: 'jag.png' 
      etc... 
     } 
    }, 
    Matches: 
     12345: { 
      User1: 'LpWgezRkC6EWS0sjXEWxhFl2' 
      User2: 'RfskjEWSkdsjkjdskjsd12fg'    
      date: '11/10/17' 
      WeekId: 19 
      etc... 
     } 
    } 
} 

正如你所看到的“匹配”节点持有的球员的信息,以便在收集视图我期待显示PLAYER1 VS player2信息。

我到目前为止的代码是这样的:

self.ref.queryOrdered(byChild: "WeekId").queryEqual(toValue: 19).observe(.value, with: { snapshot in 

    var items: [Match] = [] 

    for item in snapshot.children { 

     let snapshotValue = (item as! DataSnapshot).value as? NSDictionary 

     let pId1 = snapshotValue!["User1"] as! NSString 
     let pId2 = snapshotValue!["User2"] as! NSString 

     let match = Match(snapshot: item as! DataSnapshot) 

     items.append(match) 

    } 

    self.matches = items 

    self.collectionView?.reloadData() 
} 

我真的不知道该怎么办了第二查找到的球员的节点(我将需要2),因为它需要查找两玩家信息,全部没有超过let match = Match(snapshot: item as! DataSnapshot)的功能,否则会失败?

任何人都可以帮忙!

回答

1

您可以添加

self.ref.queryOrdered(byChild: "WeekId").queryEqual(toValue: 19).observe(.value, with: { snapshot in 

     var items: [Match] = [] 

     for item in snapshot.children { 

      let snapshotValue = (item as! DataSnapshot).value as? NSDictionary 

      let pId1 = snapshotValue!["User1"] as! NSString 
      let pId2 = snapshotValue!["User2"] as! NSString 

      fetchUserProfile(withUID: pId1, completion: { (userDict1) in 
       // Here you get the userDict 1 
       self.fetchUserProfile(withUID: pId2, completion: { (userDict2) in 
        //Here you get the user dict 2 
        let match = Match(snapshot: item as! DataSnapshot) 
        items.append(match) 
       }) 
      }) 
     } 

     self.matches = items 

     self.collectionView?.reloadData() 
    }) 

//获取用户配置文件与完成

func fetchUserProfile(withUID uid: String, completion: @escaping (_ profileDict: [String: Any]) -> Void) { 
    // New code 
    Database.database().reference().child(uid).observe(.value, with: { snapshot in 
     // Here you can get the snapshot of user1 
     guard let snapDict = snapshot.value as? [String: Any] else {return} 
     completion(snapDict) 
    }) 
} 

我不认为这对解决这个正确的方式。我建议你捕获所有用户的pID并将其保存在UserProfiles数组中。需要时,您可以从该阵列获取用户配置文件。 希望它有帮助。

+0

你好Rozario,我这样做,问题是这将不会等待第二和第三查找,因为它会创建'匹配'对象,然后将它附加到UICollectionView – Learn2Code

+0

您可以将它添加到带有完成块的函数中等待firebase数据库完成其异步获取。 第1步:获取用户配置文件1完成。 第2步:在profile1完成中获取用户profile2。 第3步:在profile2完成内创建模型对象并将其附加到项目。 –

+0

你能否用包括完成处理程序的代码修改你的答案。 – Learn2Code

相关问题