2017-10-28 135 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

相關問題