UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.