Zunächst einmal geschätzt werden, sollten Sie eine Methode in Ihrer AppDelegate
erstellen, die Ihre Token Erwerb behandelt. Dann tun Sie so etwas wie dieses
func getToken() {
//Whatever you need to do here.
UserDefaults.standard.set(Date(), forKey: "tokenAcquisitionTime")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tokenAcquired"), object: nil)
}
Erstellen Sie eine Timer-Variable in Ihrer AppDelegate
var timer: Timer!
Erstellen Sie die folgenden Methoden in der 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()
}
}
}
schließlich in Ihrer AppDelegate
‚s didFinishLaunching
, willEnterForeground
und didEnterBackground
, machen Sie folgendes
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)
}
Haben Sie den richtigen Weg gefunden, dies schon zu tun? – user805981