使用Firebase登录后,标签更新较晚



我试图解决这个简单的问题,但我绝对不明白我做错了什么。

我有两个视图控制器,LoginVCHomeVC。在LoginVC上进行身份验证后,用户进入HomeVC,在那里我有一个功能,可以检查用户是否登录并从Firebase获取数据。

HomeVC出现时,UIImageView会立即从FirebaseStorage获取一张照片,但所有标签都会在1秒后获取数据。

override func viewDidLoad() {
super.viewDidLoad()
checkIfUserLogedIn()
}
//check if loged in and fill information
func checkIfUserLogedIn() {
if FirebaseAuth.Auth.auth().currentUser?.uid != nil {
let uid = FirebaseAuth.Auth.auth().currentUser?.uid
FirebaseDatabase.Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (DataSnapshot) in
if let dictionary =  DataSnapshot.value as? [String: String] {
//update labels
self.nameLabel.text = dictionary["name"]
self.lastNameLabel.text = dictionary["lastName"]
self.ageLabel.text = dictionary["age"]
self.cityCountryLabel.text = dictionary ["cityCountry"]
self.phoneNumberLabel.text = dictionary ["phoneNumber"]
}
})
//fetch photo to the UIImageView
let storageRef = Storage.storage().reference(withPath: "usersPhoto/(uid!).jpg")
let placeHolder = UIImage(named: "placeholder.jpg")
imageViewPhoto.sd_setImage(with: storageRef, placeholderImage: placeHolder)
imageViewPhoto.contentMode = .scaleAspectFill
imageViewPhoto.layer.cornerRadius = 25
imageViewPhoto.layer.shadowColor = #colorLiteral(red: 0.8374180198, green: 0.8374378085, blue: 0.8374271393, alpha: 1)
imageViewPhoto.layer.shadowOffset = CGSize(width: 0, height: 0)
imageViewPhoto.layer.shadowRadius = 5
imageViewPhoto.layer.shadowOpacity = 0.4
imageViewPhoto.layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
imageViewPhoto.layer.borderColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
imageViewPhoto.layer.borderWidth = 0.5
} else {
return
}
}

我试过了:

DispatchQueue.main.async {
//upadte labels
self.nameLabel.text = dictionary["name"]
self.lastNameLabel.text = dictionary["lastName"]
self.ageLabel.text = dictionary["age"]
self.cityCountryLabel.text = dictionary ["cityCountry"]
self.phoneNumberLabel.text = dictionary ["phoneNumber"]
}

我也试过:

DispatchQueue.main.async(execute: {
//upadte labels
self.nameLabel.text = dictionary["name"]
self.lastNameLabel.text = dictionary["lastName"]
self.ageLabel.text = dictionary["age"]
self.cityCountryLabel.text = dictionary ["cityCountry"]
self.phoneNumberLabel.text = dictionary ["phoneNumber"]
}
})

我假设FireBaseobserveSingleEvent(of:with:)函数是异步的,并在后台线程上调用它的完成处理程序。您应该查看FireBase文档来确认这一点。

如果是这种情况,则需要将UI代码封装在对DispatchQeueue.main.async(execute:)的调用中。(所有UIKit调用都需要从主线程完成。

您呼叫DispatchQeueue.main.async的两个版本没有区别。一个版本使用";尾部闭合";语法,其中跳过函数parens和execute参数上的标签,而另一种形式使用normal";"长手";函数调用语法。两个版本的效果相同。

相关内容

  • 没有找到相关文章