How to keep the user authenticated?

1

I'm using Alamofire to submit the authentication request like this:

let user = "user"
let password = "password"

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
         .authenticate(user: user, password: password)
         .responseJSON { response in
             debugPrint(response)
       // Aqui verifico se foi autenticado e redireciono para a view principal.

}

My question is, how can I save the authentication so that the user does not have to log in again when I enter the application, in PHP I would use $_SESSION but in swift I do not know.

    
asked by anonymous 14.01.2016 / 13:57

1 answer

1

In Swift you can use the NSUserDefaults to persist these data.

To save the user and password use:

SWIFT 2

let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject("joaosilva", forKey: "username")
userDefaults.setObject("senha1234", forKey: "password")

SWIFT 3

UserDefaults.standard.set("joaosilva", forKey: "username")
UserDefaults.standard.set("senha1234", forKey: "password")

To recover the data use:

SWIFT 2

let userDefaults = NSUserDefaults.standardUserDefaults()
let username = userDefaults.stringForKey("username")
let password = userDefaults.stringForKey("password")

SWIFT 3

let username = UserDefaults.standard.string(forKey: "username")
let password = UserDefaults.standard.string(forKey: "password")
    
14.01.2016 / 17:02