Santiago carmona gonzalez Santiago carmona gonzalez - 4 years ago 164
Swift Question

Renew user token on iOS swift Application

I need to renew the user token is sending to the database for verify and process the requests from the app.

The user token expire every month for security, so I've to call the function that make the renew every 20 days or 25 days to renew the token.

I've thought on use NSTimer but when the app is closed it stops so isn't a solution.

Do you know how can i do this ?

Answer Source

Do it like this

// Get current date
let date = NSDate()
// Add 20 days to it
let tokenDaysAdded: NSDate = date.dateByAddingTimeInterval(Double(60 * 60 * 24 * 20)) as! NSDate
// Save it to your NSUserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(tokenDaysAdded, forKey: "token")

// Get the token date
let tokenDate = defaults.objectForKey("token")!
// Get current date
let now: NSDate = NSDate()

// Check if tokenDaysAdded is earler than today, then you´re ok
if tokenDaysAdded.earlierDate(now) == tokenDate as! NSObject {
    // you´re ok
// Else you need to update the token since tokenDaysAdded is greater than todays date
else {
    // tokenDaysAdded is earlier
    // Send notifcation about updating the token
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download