SwiftUI Journey Part 5: Sign In To Home View

Posted on May 10, 2022

On iOS, to transition from a SignInViewController to HomeViewController after the user successfully signs in, you just have to call the makeKeyAndVisible().

But on macOS using SwiftUI, here’s how I did it. It took me a while to get this right. And, still not entirely sure if this is the way.

This is the way

Here’s what my sign in view looks like, some parts are removed obviously for security reasons. But the conditional logic is the same.

import SwiftUI

struct SignInView: View {
   @State private var signInSuccess = false
    var body: some View {
        if signInSuccess {
        else {
           Text("I'm in sign in.").padding()

First of all, the concept of @State is still foreign to me. It is both awesome and terrifying. Terrifying because it seems there are no lifecycles to follow and might cause some logic bugs in the future. This needs more serious study but in the meantime, signInSuccess variable holds the state of whether the user successfully signs in or not.

Now, here’s my sign in function.

private func signIn() {
        if !email.isEmpty && !password.isEmpty {
            if let url = URL(string: Urls.main.authenticate) {
                let session = URLSession.shared
                var request = URLRequest(url: url)
                request.httpMethod = "POST"
                let body = "info[email]=\(email)&info[password]=\(password)"
                request.httpBody = body.data(using: .utf8)
                let task = session.dataTask(with: request) { [self]
                    data, response, error in
                    if let error = error {
                        print("Login error \(error)")
                    } else {
                        // No errors found
                        signInSuccess = true

By the time the variable signInSuccess is set to true, SwiftUI will update the parts of the view heirarchy. That means the condition below will be triggered.

if signInSuccess {

It’s frustrating how few SwiftUI for macOS tutorials are out there. Anyway, that’s all for now.