'automatic delete token in userdefaults after 6 hours in swiftui

I have two apis

  1. Login
  2. DataShow

when i login server gives me token which remains valid for only 6 hours and i am saving it in userdefaults, so that user will not have to login again and again

and when user token expires then it will show login page otherwise directly show the datashow page

can someone help me i need to find a way to remove then userdefaults token in 6 hours.



Solution 1:[1]

For that You should get difference between time of Login and time of opening app again, if difference is greater than 6 Hours then empty you user default.

When user login save current date in User Default and when application Start call onAppear function and check difference between current date using following function.

  func hours(from date: Date) -> Int {
    return Calendar.current.dateComponents([.hour], from: date, to: 
    self).hour ?? 0
  }
  

Then,

  if hours(from : loginTimeDate) > 5 {
     UserDefaults.standard.set("newvalue_or_Empty", forKey : "Your_Selected_Key")
  }

Hope This Might be Helpful.

Update as Per Desdenova Comment : -

Use this Function onAppear as well :

   func seconds(from date: Date) -> Int {
    return Calendar.current.dateComponents([.second], from: date, 
    to: self).second ?? 0
   }

This will give you seconds till you timeout of token. Then get this token and Set timer. Time Work while app is active.

   if hours(from : loginTimeDate) > 5 {
     UserDefaults.standard.set("newvalue_or_Empty", forKey : "Your_Selected_Key")
  } else {
     let timeinterval = (6*60*60) - seconds(from date: loginTimeDate)
     Timer.scheduledTimer(withTimeInterval: timeinterval, repeats: false) { timer in
         UserDefaults.standard.set("newvalue_or_Empty", forKey : "Your_Selected_Key")
         }
    } 

 

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