Sunday, November 8, 2026
HomeiOS Developmentios - Find out how to transfer to the following view upon...

ios – Find out how to transfer to the following view upon knowledge reception?

[ad_1]

I’m struggling to set off the logic answerable for altering the view on the proper time. Let me clarify.

I’ve a view mannequin that comprises a perform referred to as createNewUserVM(). This perform triggers one other perform named requestNewUser() which sits in a struct referred to as Webservices.

func createNewUserVM() -> String {
    Webservices().requestNewUser(with: Person(firstName: firstName, lastName: lastName, electronic mail: electronic mail, password: password)) { serverResponse in
        guard let serverResponse = serverResponse else {
            return "failure"
        }
        return serverResponse.response
    }
}

Now that is what’s taking place within the Webservices’ struct:

struct Webservices {
    
    func requestNewUser(with consumer: Person, completion: @escaping (Response?) -> String) -> String {
       
        
        //code that creates the specified request primarily based on the server's URL
        //...
        URLSession.shared.dataTask(with: request) { knowledge, response, error in
            guard let knowledge = knowledge, error == nil else {
                DispatchQueue.principal.async {
                    serverResponse = completion(nil)
                }
                return
            }
            let decodedResponse = attempt? JSONDecoder().decode(Response.self, from: knowledge)
            DispatchQueue.principal.async {
                serverResponse = completion(decodedResponse)
            }
        }.resume()
        return serverResponse //final line that will get executed earlier than the if assertion
    }
    
}

In order you possibly can see, the escaping closure (whose code is within the view mannequin) returns serverResponse.response (which will be both “success” or “failure”), which is then saved within the variable named serverResponse. Then, requestNewUser() returns that worth. Lastly, the createNewUserVM() perform returns the returned String, at which level this complete logic ends.

As a way to transfer to the following view, the thought was to easily test the returned worth like so:

serverResponse = self.signupViewModel.createNewUserVM()
if serverResponse == "success" {
//transfer to the following view
}

Nonetheless, after having written just a few print statements, I discovered that the if assertion will get triggered manner too early, across the time the escaping closure returns the worth, which occurs lots earlier than the view mannequin returns it. Any concept on the best way to delay that if assertion?

Thanks lots and take care!

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments