我正在处理应用程序,使用JWT身份验证。服务器端没有提供在expiry date
之后自动更新令牌的机制,但是我已经获得了一个用于刷新令牌的特殊方法。
实际上,我不知道如何正确检查expiry date
我想为Timer
设置expiry date
,但是当应用程序在后台时计时器不起作用。我还想在viewWillAppear
中检查令牌有效性,但是这样做,服务器请求的数量急剧增加,这也不够好。
任何帮助都将不胜感激
最佳答案
首先,您应该在AppDelegate
中创建一个处理令牌获取的方法。然后做这样的事
func getToken() {
//Whatever you need to do here.
UserDefaults.standard.set(Date(), forKey: "tokenAcquisitionTime")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}
在
AppDelegate
中创建计时器变量var timer: Timer!
在
AppDelegate
中创建以下方法func postTokenAcquisitionScript() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
}
func tick() {
if let time = UserDefaults.standard.value(forKey: "tokenAcquisitionTime") as? Date {
if Date().timeIntervalSince(time) > 3600 { //You can change '3600' to your desired value. Keep in mind that this value is in seconds. So in this case, it is checking for an hour
timer.invalidate()
getToken()
}
}
}
最后,在
AppDelegate
的didFinishLaunching
、willEnterForeground
和didEnterBackground
中,执行以下操作func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Your code here
NotificationCenter.default.addObserver(self, selector: #selector(postTokenAcquisitionScript), name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}
func applicationWillEnterForeground(_ application: UIApplication) {
//Your code here
NotificationCenter.default.addObserver(self, selector: #selector(postTokenAcquisitionScript), name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}
func applicationDidEnterBackground(_ application: UIApplication) {
//Your code here
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}