gpt4 book ai didi

swift - 如何从 firebase 读取数据,block with 不起作用?

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:17 26 4
gpt4 key购买 nike

我尝试从 firebase 读取数据。我制作了 observeSingleEvent,但阻止“with”不起作用,为什么?

我尝试调试,发现 block with 不起作用。userID 有正确的 ID并且引用也正确

    var ref: DatabaseReference!
var snapData: NSDictionary?
var nameString = [String]()

override func viewDidLoad() {
super.viewDidLoad()

ref = Database.database().reference()
loadData()
table.delegate = self
table.dataSource = self
table.register(UITableViewCell.self, forCellReuseIdentifier: "indentifire")
view.addSubview(table)


// Do any additional setup after loading the view.
}

// ---------------------------------------------------

//loading data from FireBase
func loadData() {
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
self.snapData = snapshot.value as? NSDictionary
})
}

// delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var temp = 0
for (_,val) in snapData! {
if val as? String == "false" {
temp += 1
nameString.append(val as! String)
}
}
return temp
}

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

this is my database
![photo](https://imgur.com/a/0UzOPJ7

最佳答案

数据库操作异步进行。映射loadData中的数据并重新加载 TableView

func loadData() {
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
if let snapData = snapshot.value as? [String:Any] {
self.nameString = snapData.values.compactMap {$0 as? String}
DispatchQueue.main.async {
self.table.reloadData()
}
}
})
}

并且在 numberOfRowsInSection 中只返回 nameString 中的项目数

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

关于swift - 如何从 firebase 读取数据,block with 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55352389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com