我正在尝试执行一个简单的功能,该功能在应用程序的后台运行计时器。
简而言之
- 应用程序启动后,就会启动10秒计时器
- 看到确认计时器已在前台启动后,我锁定了设备
- 10秒后,在后台运行应用程序的情况下,我希望看到一条日志。目前,该功能在模拟器中有效,但在设备上不可用
下面的完整代码。 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.
})
}
}
}