swift: auto logout after certain time

2.7k views Asked by At

I am developing an app which is connected to a server through .net api.

What user logs in it generate an access token which is used to make network calls.

Requirement: After 20 mins of the generation of that access token, the token gets expired and the user have to log in again to continue using the app.

How can I achieve this feature that after 20 min the user will get logout from app and redirected to the home page.

If the user is using app even after 20 min from login? how to save the access token in app and remove it once user logout.

I have seen a couple of answers in Objective c but I want the answer in swift.

2

There are 2 answers

2
Shamas S On

Save your access token to the keychain, and timestamp it.

Write a function which gets you the API token from the keychain. Each time this function accesses the access token, it should check if its timestamp is older than 20 mins it should return nil, and then you shoudl take the user to the home screen.

8
Saranjith On

Welcome to stack overflow

Short Answer

Create a timer in app delegate to track the token expiry. And reset timer when needed.

Long Answer TLDR;

To implement the feature as you have explained we need to

  • Keep track of access token expiry in app delegate only.

  • Start a timer for 20 mins when user logs in from AppDelegate.

  • Before making any API Calls access the token from app delegate (Internally you can save in any secure method for example KeyChain),
  • While accessing token from app Delegate check if timer is expired. If so present your login screen in the window.
  • If not present then make API Call and let the user do the tasks.

Advantage of this method

If you are sure that access token will expire in 20mins then without making any API calls we can logout the user from app.