swift - 将数据从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
})
**此代码的问题是我不需要该身份验证部分(没有用户必须登录我的应用程序,他们只是在输入信息)。
解决方案
您缺少-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)")
}
})
推荐阅读
- sql - 仅当记录存在时才插入 Postgres 表
- python - 重新格式化 datetime 对象以使用斜杠而不是破折号
- java - 如何在 Java webflux webclient 请求中禁用安全证书检查
- uwp - Windows 10 AppInstaller:“从 Web 访问文件时出错”
- r - ifelse() 在某些情况下缺少值,但不是全部 /R
- vba - 在 MS Access 中将多行连接成单行并计算总和
- c# - 如何在 C# 中遍历和读取对象的 ArrayLists 的 ArrayList 中的值?
- c# - 统一镜像 Oculus Rift 控制器位置以实现双边移动
- jupyter-notebook - 如何使用 %env 在 Jupyter 笔记本中连接 envvar
- c# - 是否可以在 asp.net 核心的视图包属性中间连接?