How to user UserDefaults to Save Logged in state?

5.2k views Asked by At

i'm making introdution for my app, in swift 4 but i ran intro a problem. i have a introController and HomeController view,root view is introController so i want if user logged in to HomeController from introControll, then Whenever user open app, the first view appear is HomController, ( they don't need to login again ).

I think about store login state inside of userDefaults, i don't want my app use Navigation, any idea? please help

thanks in advance

2

There are 2 answers

2
tushali_jasoliya On

When you make login save any bool value like this:

UserDefaults.standard.set("1", forKey: "isLogin")

In appdelegate check login state like this:

if UserDefaults.standard.value(forKey: "isLogin") != nil{
            //Navigate to homeviewcontroller
 }else{
            //Navigate to rootviewcontroller
 } 
5
Ahmed Elzohry On

It's very simple

You need to save state in UserDefaults when user successfully logged in like that: [Swift 3, 4]

/// call if user logged in
func saveLoggedState() {

    let def = UserDefaults.standard
    def.set(true, forKey: "is_authenticated") // save true flag to UserDefaults
    def.synchronize()

}

Then in AppDelegate in didFinishLaunchingWithOptions before return true

let def = UserDefaults.standard
let is_authenticated = def.bool(forKey: "is_authenticated") // return false if not found or stored value

if is_authenticated {
    // user logged in
    let homeController = HomeController() // create instance of HomeController or from Storyboard

    window?.rootViewController = homeController // change rootViewController to HomeController
    window?.makeKeyAndVisible() // show window
}