How can I return to the login view in a SwiftUI app

630 Views Asked by At

I am developing an iOS app using SwiftUI and the first view is a login view where you have to enter a password to continue to the next screen. Everything is working just fine but I want my app to go back to the login view each time I return to this app after using another app in the device. Here is an example of what I have:

struct ContentView: View {

    @State private var showLogin = true
    @State private var loginPassword = ""

    let correctPassword = "1234"

    var body: some View {
        Group{
            if showLogin{
                VStack{
                    TextField("Your password", text: self.$loginPassword)

                    Divider()
                    Button("Login"){
                        if self.loginPassword == self.correctPassword {
                            self.showLogin.toggle()
                        }else {
                            self.loginPassword = ""
                        }
                    }
                    .padding(8)

                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(20)
                }
            } else {
                Text("Hello world")
            }

        }
    }
}
1

There are 1 best solutions below

1
Asperi On

Here is possible approach (based on app notifications):

struct ContentView: View {
    @State private var showLogin = true
    @State private var loginPassword = ""

    let correctPassword = "1234"

    let deactivatePublisher = NotificationCenter.default.publisher(for: 
            UIApplication.didEnterBackgroundNotification)

    var body: some View {
        Group{
            if showLogin{
                VStack{
                    TextField("Your password", text: self.$loginPassword)

                    Divider()
                    Button("Login"){
                        if self.loginPassword == self.correctPassword {
                            self.showLogin.toggle()
                        }else {
                            self.loginPassword = ""
                        }
                    }
                    .padding(8)

                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(20)
                }
            } else {
                Text("Hello world")
            }
        }
        .onReceive(deactivatePublisher) { _ in
            self.loginPassword = ""
            self.showLogin = true
        }
    }
}