Search code examples
iosswiftswiftuiuserdefaults

How to conditionally load view upon app launch in SwiftUI?


I'm currently trying to implement an auto-login feature to my app using UserDefaults. What I would like to do before loading any view is get the UserDefaults email and password and call the login function from my API. If successful, go to Home view, else go to LoginView. My apologies, I'm very new to Swift and on a tight schedule with my project. Here is my code segment. I'm not sure where I can add my logic:

import SwiftUI

@main
struct MyApp: App {
    init() {
        let email = UserDefaults.standard.string(forKey: "email");
        let pw = UserDefaults.standard.string(forKey: "pw");
        
        let api = MyAppAPI()
        api.signInUser(email: email, password: pw) { result in
            //JSON response contains an 'isError' field
            let isError = result.value(forKey: "error") as! Bool
            
            if !isError {
                //successful login - what to do from here?   
            }
        }
    }
    
    var body: some Scene {
        WindowGroup {
            LoginView()
        }
    }
}

Solution

  • Here is a simple way of doing this, you can do this onAppear


    import SwiftUI
    
    struct ContentView: View {
        
        let email: String
        let pass: String
    
        init() {
            self.email = UserDefaults.standard.string(forKey: "email") ?? ""
            self.pass = UserDefaults.standard.string(forKey: "pw") ?? ""
        }
        
        @State private var result: Bool?
    
        var body: some View {
            
            Group {
                
                if let unwrappedResult: Bool = result {
                    
                    if unwrappedResult {
                        
                        Text("Home View, Welcome!")
                    }
                    else {
                        
                        Text("Wrong User or Pass, try again!")
                    }
                    
                }
                else {
                    
                    Text("loading...")
                    
                }
      
            }
            .onAppear() { loginFunction(email: email, pass: pass) { value in result = value } }
    
        }
    }
    

    func loginFunction(email: String, pass: String, completion: @escaping (Bool) -> Void) {
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(3000)) { completion(Bool.random()) }
      
    }