'Auto login using UserDefaults() not working Swift 5

I have followed some tutorials and used their methods to implement auto login for my app, but once I relaunch the app after entering the credentials, the app does not log in.

var userDefaults = UserDefaults.standard

here I initiate the user defaults feature

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
    if let safeData = data {
        if let dataString = String(data: safeData, encoding: String.Encoding.utf8) {
            print(dataString)
            if dataString == "Hello" {
                self.userDefaults.setValue(true, forKey: "UserIsLoggedIn")
                DispatchQueue.main.async {
                    self.performSegue(withIdentifier: "loginSegue", sender: self)
                }
            } else {
                DispatchQueue.main.async {
                    self.validationLabel.isHidden = false
                    self.validationLabel.text = " Username or password is incorrect. "
                    self.loginSuccessful = false
                }
            }
                    
                                
        }
    } else {
        print(error ?? "Error with data API URLSession")
    }
}.resume()

here, inside the API call. if the response from the API is "hello" which means the login was successful, i set the value to true with an identifier.

if userDefaults.value(forKey: "UserIsLoggedIn") as? Bool == true {
    performSegue(withIdentifier: "loginSegue", sender: self)
} else {}

here in the view did load I use the userDefaults to perform the segue to the next screen for future launches.. but it is not working.

initiation

viewdidload

API call



Solution 1:[1]

var userDefaults = UserDefaults() seems wrong. Use let userDefaults = UserDefaults.standard instead. Also there's no need to make this a property of your class, simply use this within your methods whereever it's needed.

Solution 2:[2]

Swift 5. Auto login myApplication According woking & help you best my try

 //First Time  key     
  // According API Response success then add 

    if !UserDefaults.standard.bool(forKey:"isLogin") { // Success

        UserDefaults.standard.set(true, forKey: "isLogin") // To do....
        UserDefaults.standard.synchronize()

    } else {  // response fail   
          // To do ....

    } 

Solution 3:[3]

Have you checked if the value is being saved in your User Defaults file? If you are running your app on the simulator, try printing the file path to your User Defaults file and try locating it. It might not fix your immediate problem but it will hopefully give you an idea as to where the problem is coming from.

Try printing the location of your User Defaults file using the following line in your AppDelegate.swift

    print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gereon
Solution 2
Solution 3 Zachary Farnes