NSTimer时发生意外崩溃

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

在applicationIdentiterBackground方法中,我调用此函数:
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)
}

这是我的应用程序进入后台时的输出:
swift - ApplicationDidEnterBackground:NSTimer时发生意外崩溃-LMLPHP
双人间休息。
在info.plist中我添加:应用程序不在后台运行:否。
告诉我我做错了什么?
编辑:
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])

最佳答案

您的基本问题似乎是对不是真正对象的东西使用AnyObject。它会导致as! Bool失败。
这里有一个操场片段,它通过允许字典中的简单值来返回存储的bool值。

var rows: [[String : Any]] = []
let i: [String : Any] = ["time": time, "Playing": false, "lastTime": 0.00, "lapNumber": 0, "min": 0]
rows.append(i)

let playing = rows[0]["Playing"]
if let playing = playing as? Bool {
    print("Bool")
} else {
    print("Something else \(String(describing: playing))")
}

关于swift - ApplicationDidEnterBackground:NSTimer时发生意外崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46662009/

10-12 04:32