Reputation: 1039
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 ?
Upvotes: 2
Views: 1531
Reputation: 38833
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
}
Upvotes: 4
Reputation: 2346
Store the date when the token was last updated or until when its valid, and renew the token when the application opens again. Thats the only way you can do this on iOS. You can't have a long running timer in the background, the system will kill it.
Another alternative is to send a remote notification when the token is about to expire or has expired, and then renew the token (it will wake the app).
Upvotes: 0