gpt4 book ai didi

swift - Firebasedata 不填充 tableView

转载 作者:行者123 更新时间:2023-11-28 14:03:52 24 4
gpt4 key购买 nike

我正在尝试从 Firebase 读取数据,并将其写入 tableView 但数据未填充 tableView
当我在读取数据的闭包内打印数据时,它打印正确,但在闭包外打印空白值。它还在 viewDidAppear

中正确打印
import UIKit
import Firebase

class UserProfileTableViewController: UIViewController, UITabBarDelegate, UITableViewDataSource {


private var gotName: String = ""
private var gotAdress: String = ""
private var gotPhone: String = ""

@IBOutlet var tableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

self.tableView.separatorColor = UIColor.gray

//Get userinfo from database

let uid = Auth.auth().currentUser!.uid
let userInfoRef = Database.database().reference().child("userprofiles/\(uid)")

userInfoRef.observeSingleEvent(of: .value, with: { (snapshot) in

// Get user value
let value = snapshot.value as? NSDictionary
let name = value?["Name"] as? String ?? ""
let address = value?["Address"] as? String ?? ""
let phone = value?["Phone"] as? String ?? ""

self.gotName = name
self.gotAdress = address
self.gotPhone = phone
print("Print inside closure in viewDidLoad\(self.gotName, self.gotAdress, self.gotPhone)") //This prints the correct data
// ...
}) { (error) in
print(error.localizedDescription)
}



let testRef = Database.database().reference().child("Test")
testRef.setValue(gotName) // Sets value to ""

print("Print inside outside in viewDidLoad\(self.gotName, self.gotAdress, self.gotPhone)") //This prints blank values
}


override func viewDidAppear(_ animated: Bool) {
print("Print in viewDidAppear closure\(self.gotName, self.gotAdress, self.gotPhone)") //This prints the correct data
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileCell") as! UserProfileCell

cell.userProfileLabel.text = gotName


return cell

}

我在 viewDidLoad 中读取数据的闭包外的 print 语句是第一个在控制台中打印的语句吗?

最佳答案

从 Firebase 或任何服务器服务获取数据是以异步方式完成的。这就是为什么当您尝试在闭包外部打印变量时它不会打印任何内容。尝试在闭包内调用 tableView.reloadData(),它会显示您想要的数据。

关于swift - Firebasedata 不填充 tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53223260/

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