我试图解决这个简单的问题,但我肯定不明白我做错了什么。
我有两个视图控制器,LoginVC
和HomeVC
。在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"]
}
})
1条答案
按热度按时间hfwmuf9z1#
我假设FireBase的
observeSingleEvent(of:with:)
函数是异步的,并且在后台线程上调用它的完成处理程序。如果是这种情况,那么您将需要将您的UI代码 Package 在对
DispatchQeueue.main.async(execute:)
的调用中。(所有的UIKit调用都需要从主线程中完成。调用
DispatchQeueue.main.async
的两个版本没有区别。一个版本使用“尾随闭包”语法,跳过函数括号和execute
参数上的标签,另一个版本使用普通的“普通”函数调用语法。两个版本的效果是相同的。