如果我的应用程序在后台超过5分钟,我想执行导航到锁屏视图控制器。这是我的代码。但有时它是有效的,它应该是有效的,有时它又不起作用。如何修复呢?
private var lockTimer: Timer?
func applicationDidEnterBackground(_ application: UIApplication) {
lockTimer = Timer.scheduledTimer(withTimeInterval: 300, repeats: false) { _ in
// Navigation code
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
lockTimer?.invalidate()
lockTimer = nil
}发布于 2018-07-25 21:52:40
发布于 2018-07-25 22:10:44
尝试以下方法:
func applicationDidEnterBackground(_ application: UIApplication) {
let defaults = UserDefaults.standard
defaults.set(Date(), forKey: "LastInactiveDate")
defaults.synchronize()
}
func applicationWillEnterForeground(_ application: UIApplication) {
let defaults = UserDefaults.standard
if let lastInactiveDate = defaults.object(forKey: "LastInactiveDate") as? Date{
let seconds = Date().timeIntervalSince(lastInactiveDate)
print("Seconds ::" , seconds)
if seconds >= 300{
//Do any thing here to lock the app
}
}
defaults.set(nil, forKey: "LastInactiveDate")
defaults.synchronize()
}https://stackoverflow.com/questions/51520274
复制相似问题