I've a simple Login app. enter username and password and click login button, i will get response from server which contains a Bool. if the Bool is true then go to next page, else show an Alert with error message.
struct ContentView : View {
@State var username: String = ""
@State var password: String = ""
@ObjectBinding var loginVM : LoginViewModel = LoginViewModel()
var body: some View {
NavigationView {
VStack {
TextField($username, placeholder: Text("Username")
TextField($password, placeholder: Text("Password")
Button(action: {
let params : [String:String] =
["username":self.username,
"password":self.password]
self.loginVM.doLogin(params:params)
}) {
Text("Login")
}
.alert(isPresented: $loginVM.isLogin) {
Alert(title: Text("Login Error"), message:
Text(loginVM.errorMessage),
dismissButton: .default(Text("Ok")))
}
}
}
}
//LoginViewModel:
class LoginViewModel : BindableObject {
let willChange = PassthroughSubject<Void,Never>()
var isLogin : Bool = false { willSet { willChange.send() } }
var errorMessage = "" { willSet { willChange.send() } }
func doLogin(params:[String:String]) {
Webservice().login(params: params) { response in
if let myresponse = response {
if myresponse.login {
self.isLogin = true // this will fire willChange.send()
self.errorMessage = ""
} else {
self.isLogin = false
self.errorMessage = myresponse.errorMessage
}
}
}
}
//and my login response is:
{ "login" : true, "error": "" } OR { "login" : false, "error": "Password Incorrect"}
THE PROBLEM IS: if login is TRUE (in the response)then -> in the ContentView '$loginVM.isLogin' becomes TRUE and Alert will Show. if login is FALSE then -> $loginVM.isLogin becomes FALSE and Alert will Not Show. I just want the OPPOSITE to happen. Means i want to show the alert only if the login is FALSE. Also If the login is true, I want to go to next page(how to do that?), else show the errorMessage in the Alert.