在Firebase中读取阵列

时间:2018-07-21 21:16:21

标签: arrays swift firebase firebase-realtime-database

在读取Firebase结构中的“用户”数组时,我需要一些帮助,如下所示。

Firebase structure

我使用以下功能从Channels表中获取数据。

func observeChannels(channelId: String, onSuccess: @escaping (ChannelModel) -> Void) {
    DB_REF_CHANNELS.child(channelId).observeSingleEvent(of: .value) { (snapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let channel = ChannelModel.transformChannel(dict: dict, key: snapshot.key)
            onSuccess(channel)
        }
    }
}

然后将其传递给ChannelModel类,以便我可以获取每个单独的数据。

class ChannelModel {
var channelId: String?
var channelName: String?
var ownerId: String?
var users: Dictionary<String, Any>? // Array of users }

extension ChannelModel {
static func transformChannel(dict: [String: Any], key: String) -> ChannelModel {
    let channel = ChannelModel()
    channel.channelId = key
    channel.channelName = dict["channelName"] as? String
    channel.ownerId = dict["ownerId"] as? String
    channel.users = dict["users"] as? Dictionary<String, Any>
    return channel
}}

然后调用observeChannels函数,该函数向我返回所有通道的对象。

observeChannels(channelId: channelId, onSuccess: { (channel) in
            self.channels.insert(channel, at: 0)
            self.tableView.reloadData()

            let user = channel.users!
            print(user)
        })

当我运行上面的函数来获取用户时,我的输出如下:

["pZaEJ5aAAkR7WzgIJ4Wqf10jXot1": 1, "asdasldljAlsjkasldj": 1]

我想知道如何获取键值-即:

["pZaEJ5aAAkR7WzgIJ4Wqf10jXot1", "asdasldljAlsjkasldj"]

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试一下:

let usersDictionary = channel.users!
usersArray = Array(usersDictionary.keys)
print(usersArray)

代替:

let user = channel.users!
print(user)