How can I make a NavigationButton
to wait for the server response before going to the next view ?
I\'ve tried something like this
Naviga
Sorin, at least in my understanding SwiftUI is designed only for the presentation layer, it's not supposed to replace your model. And it's "reactive", unlike UIKit, so making the view perform model-like actions is, by design, very hard.
I would approach the task like this :
class LoginModel : BindableObject {
var didChange = PassthroughSubject<LoginModel, Never>()
private(set) var username: String? {
didSet {
didChange.send(self)
}
}
func load() {
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.username = "Sorin"
}
}
}
This is the model object encapsulating our login code. The async operation is here simulated by a simple delay.
And, then, the view :
public struct LoginScreen: View {
@ObjectBinding var loginObject = LoginModel()
public var body: some View {
Group {
if login.username == nil {
Text("Trying to login, please wait...")
} else {
Text("Successful login, the username is \(loginObject.username!)")
}
}.onAppear {
self.loginObject.load()
}
}
}
There are better ways of "linking" with the model object, but we're looking here only at a bare-bone example, obviously.
Your NavigationButton
will only link to the LoginScreen, without any other code or trigger.
The screen will initially display Trying to login, please wait...
and after 5 sec will change to Successful login, the username is Sorin
. Obviously you could go wild and replace my text here with anything you may want.