简体   繁体   中英

swiftUI: Navigate to Home screen after Login Completed. Navigating Views by Button click

I'm doing a sign-in screen. after the sign-in button click, I'll do an API call on the response I will redirect the user to home screen.

Q - How to navigate from one View to Another by a button click with some action.

I've tried this, Programatically navigate to new view in SwiftUI

But I'm getting an error like,

"Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type"

Please help me to resolve it.

There is an issue with some View ATM (hope it will be fixed soon).

In order to use code posted, you will need to write something like:

struct ContentView: View {

    @EnvironmentObject var userAuth: UserAuth 

    @ViewBuilder
    var body: some View {
        if !userAuth.isLoggedin {
            return LoginView()
        } else {
            return NextView()
        }
    }
}

At the list, at the moment of writing, this was the only thing working for me - both for body and for Group.

Reference for future: date 24 Oct 2019.

Alternatively look at SceneDelgate.swift where you can set the root view of the key window to whatever you want.

In your situation when there is a successful login you can signal the change of state to the SceneDelegate (such as by Notification). Then have the app set the root view controller to your main View (as a UIHostingController).

For example:

In your SceneDelegate class add: var currentScene: UIScene? // need to keep reference var currentScene: UIScene? // need to keep reference

Then inside the func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)

Save a reference to the scene in the variable declared above.

self.currentScene = scene

Next, add a listener to when you want to change the key window with the new view:

 var keyWindow: UIWindow?

 NotificationCenter.default.addObserver(forName: .newUser, object: nil, queue: .main) { [weak self] (notification) in

      guard let windowScene = self?.currentScene as? UIWindowScene else { return }

      keyWindow = UIWindow(windowScene: windowScene)
      keyWindow?.rootViewController = UIHostingController(rootView: Text("hello"))
      keyWindow?.makeKeyAndVisible()

    }

Just set the Notification to post whenever you need and replace the Text with whatever View you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM