首页 > 解决方案 > 将数据从firebase加载到标签?

问题描述

我在 firebase 中有数据,我想用 Swift 将它们加载到 UILabel 中。

我的数据结构如下:

like-1bf89addclose
 artists
 -LP6zVO8iekRMMOWe7nm
 artistGenre: pop
 artistName: postmalone
 id: 920930

我的快速代码如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

   ref = FIRDatabase.database().reference()
    refHandle = ref.observe(FIRDataEventType.value, with: {(snapshot) in
        let dataDict = snapshot.value as! [String: AnyObject]

        print(dataDict)

    })

    ref.child("artists").observeSingleEventOfType(.value, with: {(snapshot) in
        let artist = snapshot.value!["artistName"] as! String
        let genre = snapshot.value!["artistGenre"] as! String

        self.artistlLabel.text = artist
        self.genreLabel.text = genre

    })
}

我的错在哪里?我尝试过在线搜索,但大多数示例仅说明如何将输入放入 tableviews,它有不同的代码,我试图理解和重组但不能。我知道我的裁判一定有问题,但我想不通。

我正在关注 youtube 教程,这很有效:

let userID: String = (FIRAuth.auth()?.currentUser?.uid)!
ref.child("Users").child(userID).observeSingleEventOfType(.value, with: {(snapshot) in
    let email = snapshot.value!["Email"] as! String
    let password = snapshot.value!["Password"] as! String

    self.emailLabel.text = email
    self.passwordLabel.text = password

})

**此代码的问题是我不需要该身份验证部分(没有用户必须登录我的应用程序,他们只是在输入信息)。

标签: swiftfirebasefirebase-realtime-database

解决方案


您缺少-LP6zVO8iekRMMOWe7nm参考中的级别。尝试这个:

ref.child("artists/-LP6zVO8iekRMMOWe7nm").observeSingleEventOfType(.value, with: {(snapshot) in
    let artist = snapshot.value!["artistName"] as! String
    let genre = snapshot.value!["artistGenre"] as! String
    print("\(artist) \(genre)")

    self.artistlLabel.text = artist
    self.genreLabel.text = genre
})

如果要加载所有艺术家,可以加载/artists然后循环结果:

ref.child("artists/-LP6zVO8iekRMMOWe7nm").observeSingleEventOfType(.value, with: {(snapshot) in
  for child in snapshot.children.allObjects as! [DataSnapshot] {
    let artist = child.value!["artistName"] as! String
    let genre = child.value!["artistGenre"] as! String
    print("\(artist) \(genre)")
  }
})

推荐阅读