swift - 在 UITableView 中显示 Firebase 数据
问题描述
我对 Swift 语言非常陌生。我只是想提取我在 Firebase 中收集的企业名称并将它们显示在我的 UITableView
我已经尝试进行了一些更改。首先,我检查并更改了 Firebase 权限,以便可以读取它。作为 swift 新手,我尝试使用 Firebase CocoaPods 附带的不同功能。
class businessTableViewController: UITableViewController {
var name = [String]()
var ref: DatabaseReference!,
business = [eventStruct]()
struct eventStruct{
let sName: String!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadBusinesses()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadBusinesses(){
ref = Database.database().reference()
ref.child("name").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let valueDictionary = snapshot.value as? [AnyHashable:String]{
let name = valueDictionary["name"]
self.business.insert(eventStruct(sName: name) , at: 0)
}
})
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return business.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "businessCell", for: indexPath)
let label1 = cell.viewWithTag(1) as! UILabel
label1.text = business[indexPath.row].sName
return cell
}
解决方案
编辑:此答案不能解决您的问题,请参阅评论。
首先,当视图控制器消失时,你应该移除观察者,所以你应该持有对监听器的引用:
class businessTableViewController: UITableViewController {
var ref: DatabaseReference!
var handle: DatabaseHandle!
func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
}
func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadBusinesses()
}
func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let handle = handle {
ref.removeObserverWithHandle(handle)
}
}
你valueDictionary
应该看起来像:
[
0: ["address": "...", ...],
1: [...],
...,
]
但你只是在做valueDictionary["name"]
不存在的事情。如果您需要在服务器中的值更新时获取更新,您可能希望使用.value
not .childAdded
。business
此外,在更新之前删除所有以前的值。你应该:
func loadBusinesses() {
handle = ref.child("name").queryOrderedByKey().observe(.value) { (snapshot) in
guard let valueDictionary = snapshot.value as? [String: Any] else { return }
self.business.removeAll()
for (index, value) in valueDictionary.enumerated() {
if let name = (value as? [String: String])?["name"] {
self.business.insert(eventStruct(sName: name), at: 0)
}
}
}
}
注意:可能有错别字。
推荐阅读
- mysql - 显示所有组件状态已删除、存档、报告的案例
- python-3.x - 使用 selenium 设置 Chromedriver 时找不到文件错误
- python - 如何在 python pandas 中添加趋势箭头?
- python - 使用 discord.py 从另一个 cog 导入函数
- ios - Xcode 签名错误 - 操作无法完成。(OSStatus 错误 -2147416032。)
- c# - 这里叫什么:return _()
- xcode - 任何为 react-native 应用程序(iOS 和 Android)自动增加内部版本号和构建版本的工具
- c - concerning about write function,
- android - Android multi-user: get current user info
- python-3.x - 如何在 gensim 模型中查找令牌的数量