尝试从Firebase实时数据库获取数据

时间:2019-04-09 17:26:45

标签: swift firebase

我正在尝试从Firebase中的实时数据库中获取数据。 我在这里看到了一些答案,但是找不到我理解并为我工作的解决方案。 这是我的代码:

func ReadTeamPlayers(teamName name: String, completion: @escaping ([Player]?) -> Void) {
    var playersArray = [Player]()
    ref.child(name).observeSingleEvent(of: .value) { (snapshot) in
        if let postDict = snapshot.value as? Dictionary<String, Any>{
            for dict in postDict {
                playersArray.append(Player(name: dict[snapshot.key] as! String, rank: dict[snapshot.value]))
            }
        }
    }
}

在播放器初始化程序中,我需要获取播放器的名称和等级。 我的Firebase看起来像这样:

TEAM1
   ---player1: 10
   ---player2: 5
   ---player3: 6

playerX现在是玩家的名字,数字是玩家的等级。 我如何获取每个玩家的信息并在以后使用? 我尝试了几件事,但没有一件对我有用。

编辑:我将上面的代码更改为当前代码,这是我现在得到的错误:

Value of tuple type '(key: String, value: Any)' has no member 'subscript'

2 个答案:

答案 0 :(得分:1)

您需要

dic.forEach {
    let player = Player(playerName:$0.key, playerRank:$0.value) 
    arr.append(player)
}

OR

let arr = dic.map { Player(playerName:$0.key, playerRank:$0.value)  }

更改响应

func ReadTeamPlayers(teamName name: String, completion: @escaping ([Player]?) -> Void) {

func ReadTeamPlayers(teamName name: String, completion: @escaping ([Player]?) -> Void) {
    ref.child(name).observeSingleEvent(of: .value) { (snapshot) in
        if let mPlayer = snapshot.value as? [String:Int] {
              var arr = [Player]()
              mPlayer.forEach {
               let player = Player(playerName:$0.key, playerRank:$0.value) 
               arr.append(player)
             }
             completion(arr)

        }else{
             completion(nil)
        }
    }
}

答案 1 :(得分:0)

尝试一下,您正在使用带有泛型的奇怪代码。保持简单

func ReadTeamPlayers(teamName name: String, completion: @escaping ([Player]?) -> Void) {
    var playersArray = [Player]()

    ref.child(name).observeSingleEvent(of: .value) { (snapshot) in

        guard let dictionary = snapshot.value as? [String: Any] else {
            print("empty snapshot")
            return
        }

        for dict in dictionary {
            print("playerName = \(dict.key)")

            if let playerRank = dict.value as? Int {
                print("playerRank = \(playerRank)")

                let player = Player(name: dict.key, rank: playerRank)
                playersArray.append(player)
            }

        }

    }
}