Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to authenticate a user after login (for auto login)?

I'd like to use an auto-login function. So when the user opens the app, he gets delegated to a "login screen". When he logged in successfully he should be directed to his account. I call this the "account screen". Now when the user restarts the app, he should directly get directed to his account, without seeing the "login screen".

The login function already works fine in my project (username and password are saved in UserDefault), but every time I close the app, I have to login again. So my question is: How do auto login the user? Or better said: How do I check if the data (saved in UserDefault) is the same as in the database (MYSQL)?

like image 924
filou Avatar asked Apr 24 '12 09:04

filou


1 Answers

  1. For the first time when the user login, you save the user credentials in iPhone's keychain.
  2. When the app is opened again, you check whether user credentials are present in keychain and if yes, you code should call the login logic and do auto login and go to screen after login screen. If no, then you should show login screen. You can do this logic in AppDelegates applicationDidFinishLaunching.
  3. Whenever user clicks the logout button, remove user credentials from keychain first, and go back to login controller.

Simply you add login credentials to keychain when user logs in and only remove it once user clicks the logout button. If user quits the app without logout then the credentials will still be in keychain and you can retrieve them when user returns to the app.

EDIT: I think I must add one more thing..If your login logic takes time (like you login using web request or something), put the login logic code in your Login ViewController rather than ApplicationDelegate, and use any Activity Indicator during auto login process.

EDIT : I edited the entire answer, replaced NSUserDefault with Keychain. This thread explains why.

like image 176
Krishnabhadra Avatar answered Oct 05 '22 13:10

Krishnabhadra