Ask Your Question
0

How to automatically navigate to a new view in SwiftUI upon successful login through HTTP request?

asked 2022-04-07 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-05-15 01:00:00 +0000

huitzilopochtli gravatar image

You can achieve this by using the @State property wrapper and the NavigationLink view. Here's an example code:

import SwiftUI

struct ContentView: View {
    @State private var username = ""
    @State private var password = ""
    @State private var isLoggedIn = false

    var body: some View {
        NavigationView {
            VStack {
                TextField("Username", text: $username)
                    .textFieldStyle(RoundedBorderTextFieldStyle())

                SecureField("Password", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())

                Button(action: login) {
                    Text("Login")
                        .padding()
                        .foregroundColor(.white)
                        .background(Color.blue)
                        .cornerRadius(10)
                }
            }
            .padding()
            .navigationTitle("Login")
            .navigationBarTitleDisplayMode(.inline)
            .sheet(isPresented: $isLoggedIn) {
                Text("Logged in!").padding()
            }
        }
    }

    func login() {
        // Make HTTP request to login API
        // If successful, set isLoggedIn to true and navigate to new view
        isLoggedIn = true
    }
}

In this code, the @State property wrapper is used to keep track of the username, password, and login status. The NavigationLink view is used to navigate to a new view upon successful login.

When the user taps the "Login" button, the login function is called. Inside this function, you can make an HTTP request to a login API using the username and password values. If the login is successful, you can set isLoggedIn to true.

The new view is displayed using the sheet modifier. By setting the isPresented parameter to true, the new view is displayed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-07 11:00:00 +0000

Seen: 13 times

Last updated: May 15 '21