我正在尝试执行一个简单的功能,该功能在应用程序的后台运行计时器。
简而言之,
下面的完整代码。 You can also download the app itself to try。
[咨询了诸如as this之类的流行答案之后(还包含有关Timer是否在后台实际运行的矛盾答案),我并不完全是该主题上权威的答案。
感谢您的帮助。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var timer : Timer?
if timer == nil {
NSLog("Timer started")
timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true, block: {_ in NSLog("After 10 seconds show up") //this will not work on a device
//Also, I get the error: Can't end BackgroundTask: no background task exists with identifier 1 (0x1), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.
})
}
}
}