gpt4 book ai didi

swift - ApplicationDidEnterBackground : NSTimer 时意外崩溃

转载 作者:搜寻专家 更新时间:2023-11-01 06:31:32 24 4
gpt4 key购买 nike

昨天,我问过,因为我的后台定时器有问题,我找到了一个解决方案让它工作,但现在,当我的应用程序进入后台时我遇到了问题。

在后台运行:

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

这是我的应用程序进入后台时的输出:

enter image description here

The Double is interval.

In Info.plist I add : Application does not run in background : NO.

让我知道我做错了什么?

编辑:

Initialization of rows in viewDidLoad method

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 表示失败。

这是一个 playground 片段,它通过允许字典中的简单值来取回存储的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com