Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swiftui

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.

like image 380
Azhagusundaram Tamil Avatar asked Mar 04 '23 06:03

Azhagusundaram Tamil


2 Answers

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.

like image 172
Miknash Avatar answered Mar 05 '23 21:03

Miknash


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

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.

like image 37
Cenk Bilgen Avatar answered Mar 05 '23 21:03

Cenk Bilgen