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?
- 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