之后发送给我的新视图依赖于一个缓存的变量。我没有使用线程的经验,但我认为机器继续运行在主线程上,而另一个线程执行"getVIN"-function。我不关心UI是否“睡眠”。有没有办法强制它在"getVIN"-function结束之前不继续?
func verify() {
if self.email != "" && self.pass != "" {
Auth.auth().signIn(withEmail: self.email, password: self.pass) {
(res, err) in
if err != nil {
print(err!.localizedDescription)
self.error = err!.localizedDescription
self.alert.toggle()
return
}
print("success")
//getVIN, finds a number from a database in Firestore, with the users email, and uploads
//it to UserDefault
self.getVIN(email: self.email)
UserDefaults.standard.set(true, forKey: "status")
UserDefaults.standard.set(self.email, forKey: "email")
print(UserDefaults.standard.string(forKey: "email"))
//when i am finished i get sent to a new View with this function
//the new View uses the cached email, but the getVIN-function is not finished until after i am redirected to the new page.
NotificationCenter.default.post(name: NSNotification.Name("status"), object: nil)
}
}
else {
self.error = "The information is wrong"
self.alert.toggle()
}
}发布于 2020-07-09 22:53:48
你可以做这样的事情。您可以将getVin的结果存储在已发布的属性中,然后使用它来加载要加载的目标视图。
这是一个伪代码,但它应该让您知道该做什么。
@Published var vin = getVin()
// In SwiftUI
if !vin {
ProgressView()
} else {
TargetView()
}此外,如果getVIN方法在后台运行,则它应该有一个完成处理程序。完成处理程序将在该方法中的数据库操作完成后执行。然后,您可以在完成处理程序中更改视图。
仅供参考,在SwiftUI中使用通知更改视图是一种错误的做法。出于完全相同的原因,Combine也被引入。在this article中了解它。
https://stackoverflow.com/questions/62814627
复制相似问题