2

I am in a login page and when I press the login button, if the login was completed without errors I want to navigate to a new view, if the login failed I want to stay on the same view. Here is my code:

struct LogIn: View {

    @State var mesaj = ""
    @State private var email = ""
    @State private var password = ""
    @EnvironmentObject var model: Model

    var body: some View {
        NavigationView {
            VStack {
                // EMAIL
                TextField("E-mail", text: $email).textFieldStyle(RoundedBorderTextFieldStyle())

                // PASSWORD
                TextField("Password", text: $password).textFieldStyle(RoundedBorderTextFieldStyle())

                // this is the login button
                Button(action: {
                    loginRequest(link: "https://someapi.com", email: self.email, password: self.password) // this is the login request
                    let seconds = 5.0
                    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
                        self.mesaj = message
                        if message == "You are now logged in"
                        {
                            // here I want to navigate to a new view
                        }
                    }
                }) {
                    Text("LogIn")
                }
                Text(mesaj)
                Spacer()
            }
        }
    }
}

Thanks!

1

1 Answer 1

1

Re-arrange your views, such that

instead of going directly to your LogIn view, have an intermediate view with something like this:

struct PreLogIn: View {

@State var loggedInSuccess = false // that you pass into the LogIn() view
// or 
@EnvironmentObject var model: Model  // with a @Published var loggedInSuccess = false 

var body: some View {
     Group {
        if model.loggedInSuccess {
            YourNextView()
        }
        else {
            LogIn()
        }
    }
}
}

then in your LogIn() view button action:

model.loggedInSuccess = true
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.