2017-07-24 113 views
0

我正在開發使用JWT身份驗證的應用程序。服務器端在expiry date之後沒有提供自動更新令牌的機制,但我已經提供了一個用於刷新令牌的特殊方法。其實我不知道如何正確檢查expiry date。我想爲expiry date設置Timer,但是當應用程序在後臺時定時器不工作。我還想過在viewWillAppear中檢查令牌有效性,但是通過這樣做,服務器請求的數量急劇增加,這也不夠好。在ios上刷新JWT身份驗證令牌

任何幫助,將不勝感激

+0

你找到了正確的方法嗎? – user805981

回答

1

首先,你應該建立在你的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() 
     } 
    } 
} 

最後下面的方法,在你的AppDelegatedidFinishLaunchingwillEnterForegrounddidEnterBackground,請執行以下操作

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) 
}