Search code examples
iosuserdefaults

Persisting data in iOS app


I am new to iOS. I want to save authentication token recieved from a REST API to use in further api calls without requiring a login. Currently I am using UserDefaults to store this token. This token works fine unless app is completely closed. Relaunching the app again takes me to login screen.

Saving the token like this

UserDefaults.standard.setValue(authToken, forKey: "auth_token")
UserDefaults.standard.synchronize() // Now this call is derpecated. Framework handles this call at proper places.

LoginViewController

override func viewDidLoad(){
   super.viewDidLoad()

   if UserDefaults.standard.string(forKey: "auth_token") != nil { 
        self.performSegue(withIdentifier: "login_success", sender: self)
   }
}

But the issue is how can I persist this token even after the app was completely closed ?

EDIT

I have also tried syncing UserDefaults within applicationWillTerminate methods of AppDelegate class just to make sure but that even doesn't work.


Solution

  • Nothing wrong with the UserDefaults. Just wrapping the triggering segue call in main queue was required to properly work.

    override func viewDidLoad() {
         super.viewDidLoad()
    
         if UserDefaults.standard.string(forKey: "auth_token") != nil {
           DispatchQueue.main.async {
             self.performSegue(withIdentifier: "login_success", sender: self)
           }
         }          
    }