GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Login architecture question

Forums > SwiftUI

Hi there,

I'm implementing a login functionality in my app and have some difficulties with architecture. Could you guide me what is a good practice for such tasks?

  1. In the main Scene I show MainView or LoginView based on factory.isAuthorized
import SwiftUI

@main
struct TestApp: App {

    @StateObject var factory = MyFactory()

    var body: some Scene {
        WindowGroup {
            if factory.isAuthorized {
                MainView().environmentObject(factory)
            } else {
                LoginView().environmentObject(factory)
            }
        }
    }
}

In the factory ObservableObject I have a saveSession func. It changes isAuthorized to true in the end.

final class MyFactory: ObservableObject {

    @Published var isAuthorized: Bool = false

    func saveSession(session: String) {
        // here some code
        isAuthorized = true
    }

The next piece is LoginViewModel. The login func does a HTTP request, gets response and passes token to the completion handler.

class LoginViewModel: ObservableObject {

    func login(email: String, password: String, completion: (String)->Void) {
        // run http request
        // read response
        completion("here is token from server")
    }
}

The final piece is my LoginView where I have a buton "Login" that calls model.login func and then passes token to my factory.

Button(
    action: {
        model.login(email: username, password: password) { session in
            factory.saveSession(session: session)
        }
    },
    label: {
            Text("Login")
    }
)

What do you think about that implemetation?

Thank you

3      

Hi @yurytom, i did same, so (for me) it is good.

3      

Hi @linkiliz , This is great to hear. Thank you.

3      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.