简体   繁体   中英

SwiftUI force wait on main thread

The new View i am getting sent to afterwards is dependent on a cached variable. I am not experienced with threads, but i think the machine continues on the main thread while another thread does the "getVIN"-function. I dont care if the UI "sleeps". Is there a way to force it so it doesn't continue until the "getVIN"-function is finished?

    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()
        }
    }

You can do something like this. You can store the result of getVin in a Published Property and then use it to load the target view you want to load.

This is a pseudo code, but it should give you an idea of what to do.

@Published var vin = getVin()

// In SwiftUI
if !vin {
  ProgressView()
} else {
  TargetView()
}

Also, the getVIN method should be having a completion handler if it runs in background. The completion handler will execute after the database operations are done in that method. You would then change your view in completion handler.

FYI, using notification for changing the Views in SwiftUI is a wrong practice. For exact same reasons Combine was introduced. Learn about it in this article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM