【发布时间】:2020-01-28 14:56:47
【问题描述】:
我正在制作这个应用程序,用户可以在其中对其他用户的简历提供反馈。我将反馈存储在 firebase 实时数据库中。在我的 FeedbackViewController 中,我有一个表视图,需要访问我的数据库上的 totalFeedbackNum 以填充我的表视图,但是我收到了一个错误。下面的注释代码应该是代码,但它抛出了错误:Unexpected non-void return value in void function。
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
}
我认为我应该使用完成处理程序,但我不知道如何使用。我正在使用 Swift 5。
编辑: 我按照 cmets 中的第一个链接得到了这个,但它仍然无法正常工作:
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 得到快照 有快照
【问题讨论】:
-
从 Firebase 取回数据后,您确实需要调用完成处理程序。请参阅stackoverflow.com/a/37925384、stackoverflow.com/questions/52972911/…、stackoverflow.com/a/56314312 以及此列表中的更多内容:stackoverflow.com/…
-
我尝试了第一个链接,但它不起作用,我应该如何调整我添加到问题中的已编辑代码?感谢您的评论
-
永远不要在
numberOfRows中异步加载数据。将viewDidLoad中的记录(一次)加载到数组中,并在numberOfRows中返回<array>.count。 -
我如何将数据传递给 numerOfRows?
-
在
numberOfRows中,您必须返回数据源数组中的项目数,仅此而已。
标签: swift firebase firebase-realtime-database