昨天,我問,因爲我的計時器在後臺有問題,我找到了一個解決方案,使其工作,但現在,當我的應用程序進入後臺時遇到問題。在後臺ApplicationDidEnterBackground發生意外的崩潰:NSTimer
運行:
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
這是我的計時器:
let interval = 0.01
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector:#selector(ViewController.updateTimer), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
這是我updateTimer功能:
func updateTimer() {
var j = 0
for _ in rows {
if (rows[j]["Playing"] as! Bool == true) {
rows[j]["time"] = (rows[j]["time"] as! Double + interval) as AnyObject
rows[j]["lastTime"] = (rows[j]["lastTime"] as! Double + interval) as AnyObject
}
if (rows[j]["lastTime"] as! Double > 60.0) {
min[j] += 1
rows[j]["lastTime"] = 0.00 as AnyObject
}
j += 1
}
}
在我applicationDidEnterBackground方法我調用這個函數:
func backgroundTimer() {
print("background") // This Print works fine
timer.invalidate() // Never works
interval = 1.00 // Crash when interval change from 0.01 to 1.00
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector:#selector(ViewController.updateTimer), userInfo: nil, repeats: true)
}
這是我的輸出,當我的應用程序在後臺輸入:
的是雙間隔。
In Info.plist我補充:應用程序不會在後臺運行:NO。
讓我知道我做錯了什麼?
編輯:行
初始化在viewDidLoad方法
let i: [String : AnyObject] = ["time": time as AnyObject, "Playing": false as AnyObject, "lastTime": 0.00 as AnyObject, "lapNumber": 0 as AnyObject, "min": 0 as AnyObject]
rows.append(i as [String : AnyObject])
rows [j] [「Playing」]的值顯然爲零。 –
@AmeyaVichare感謝您的回答。它不能爲零,它不是前景零,我不明白爲什麼它可以在後臺 – pierreafranck
你如何初始化行?請張貼代碼... –