从Swift 5中的firebase实时数据库返回int
我正在制作这个应用程序,用户可以在其中对其他用户的简历进行反馈。我将反馈存储在firebase实时数据库中。在我的FeedbackViewController中,我有一个tableview,需要访问数据库上的totalFeedbackNum以填充我的tableview,但是我遇到了一个错误。下面的注释代码是代码应该是的,但它抛出了错误:void函数中意外的非void返回值从Swift 5中的firebase实时数据库返回int,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,我正在制作这个应用程序,用户可以在其中对其他用户的简历进行反馈。我将反馈存储在firebase实时数据库中。在我的FeedbackViewController中,我有一个tableview,需要访问数据库上的totalFeedbackNum以填充我的tableview,但是我遇到了一个错误。下面的注释代码是代码应该是的,但它抛出了错误:void函数中意外的非void返回值 func tableView(_ tableView: UITableView, numberOfRowsInSec
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// var ref: DatabaseReference!
// ref = Database.database().reference()
// let uid = Auth.auth().currentUser?.uid
// ref.child("usernames/\(uid!)/profile/feedback/totalFeedbackNum").observeSingleEvent(of: .value, with: { (snapshot) in
// let value = snapshot.value as? NSDictionary
// let totalFeedbackNum = value?["totalFeedbackNum"] as? Int ?? 0
// return totalFeedbackNum //this throws "Unexpected non-void return value in void function"
// }) { (error) in
// print(error.localizedDescription)
// }
let totalFeedbackNum = 3
return totalFeedbackNum
}
我想我应该使用一个完成处理程序,但我不知道如何使用。我和斯威夫特5一起工作
编辑:
我按照评论中的第一个链接,得到了这个,但仍然不起作用:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let uid = Auth.auth().currentUser?.uid
var ref: DatabaseReference!
ref = Database.database().reference()
var totalFeedbackNum = 1
print("Starting observing")
ref.child("usernames/\(uid!)/profile/feedback/totalFeedbackNum").observe(.value, with: { (snapshot: DataSnapshot!) in
print("Got snapshot")
let value = snapshot.value as? NSDictionary
totalFeedbackNum = value?["totalFeedbackNum"] as? Int ?? 0
})
print("Returning totalFeedbackNum: \(totalFeedbackNum)");
return totalFeedbackNum
}
此代码打印:
开始观察
正在返回totalFeedbackNum:1
开始观察
正在返回totalFeedbackNum:1
获取快照
抓到快照了,所以我找到了。正如瓦迪安指出的,我需要声明一个totalFeedbackNum全局变量,我最初将其设置为0。在viewDidLoad中执行以下操作:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let uid = Auth.auth().currentUser?.uid
var ref: DatabaseReference!
ref = Database.database().reference()
ref.child("users/\(uid!)/profile/feedback/totalFeedbackNum").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
self.totalFeedbackNum = value?["totalFeedbackNum"] as? Int ?? 0
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
}
希望这能帮助别人。
干杯
Jack一旦从Firebase获得数据,您确实需要调用完成处理程序。请看,可能还有更多信息:我尝试了第一个链接,但没有成功,我应该如何调整添加到问题中的已编辑代码?感谢您的评论永远不要在
numberOfRows
中异步加载数据。将viewDidLoad
中的记录(一次)加载到一个数组中,并在numberOfRows
中返回.count
。然后如何将数据传递到numberOfRows?在numberOfRows
中,您必须返回数据源数组中的项数,而不是其他。