【问题标题】:Is it possible to display the 'name' of a firebase node as well as its value in Xcode?是否可以在 Xcode 中显示 firebase 节点的“名称”及其值?
【发布时间】:2019-05-08 09:27:34
【问题描述】:

我试图在我的应用程序中显示用户 ID,但是 UID 非常随机,并且每个用户 ID 旁边都有一个名称,是否可以同时显示节点的名称及其值?

我的 firebase 数据库

我想显示名称“Andy”以及 UID“uLUnOelxABYl3lCtLz2Of5Yfnvc2”

我已对其进行设置,以便应用从我的 Firebase 接收值。

这是我的代码:

class TestViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        cell?.textLabel?.text = list[indexPath.row]
        return cell!
    }


    @IBOutlet weak var tableView: UITableView!

    var ref: DatabaseReference!

    var list = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self


        if FirebaseApp.app() == nil {
            FirebaseApp.configure() }

        ref = Database.database().reference()

        ref?.child("users").observe(.childAdded, with: { (snapshot) in

            let list1 = snapshot.value as? String
            if let actualList = list1 {
                self.list.append(actualList)

                self.tableView.reloadData()
            }
        }
     )
    }
}

这是我回来的。但是我想显示的是旁边带有这些值的名称列表,就像这样(photoshop) results

PHOTOSHOP RESUTLS

【问题讨论】:

    标签: swift xcode firebase firebase-realtime-database nodes


    【解决方案1】:

    关于documentation FIRDataSnapshot 有属性key,所以我想你可以用它来匹配值,例如:

    /// e.g. use dictionary instead of Array
    //var list = [String] ()
    var list = [AnyHashable: String]()
    ...
    
    ref?.child("users").observe(.childAdded, with: { (snapshot) in
    
            let key = snapshot.key as? Hashable
            let value = snapshot.value as? String
            if let actualValue = value, let actualKey = key {
                self.list[key] = actualValue
                self.tableView.reloadData()
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多