[英]Making NSTimer run in the background on a physical device
I have a timer app that I have made.我有一个我制作的计时器应用程序。
When I run it on the iPhone X on the simulator, the timer will run in the background just fine, but when I test it on my physical device (iPad Pro), it does not run in the background.当我在模拟器上的 iPhone X 上运行它时,计时器会在后台正常运行,但是当我在我的物理设备(iPad Pro)上测试它时,它不会在后台运行。
Is this a glitch on the simulator's behalf, or something that I am not aware of, or is there something I need to change about my app to make it work in the background on PHYSICAL DEVICES as well?这是模拟器的故障,还是我不知道的问题,还是我需要更改我的应用程序以使其在物理设备的后台运行?
Thanks谢谢
In DidBackground:在 DidBackground 中:
In WillForeground:在 WillForeground 中:
Find below sample code:找到以下示例代码:
In Appdelegate:在 Appdelegate 中:
Declaration:宣言:
var backgroundUpdateTask: UIBackgroundTaskIdentifier!
var backgroundTaskTimer:Timer! = Timer()
Implementation:执行:
func doBackgroundTask() {
DispatchQueue.global(qos: .default).async {
self.beginBackgroundTask()
if self.backgroundTaskTimer != nil {
self.backgroundTaskTimer.invalidate()
self.backgroundTaskTimer = nil
}
//Making the app to run in background forever by calling the API
self.backgroundTaskTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.startTracking), userInfo: nil, repeats: true)
RunLoop.current.add(self.backgroundTaskTimer, forMode: RunLoopMode.defaultRunLoopMode)
RunLoop.current.run()
// End the background task.
self.endBackgroundTask()
}
}
func beginBackgroundTask() {
self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(withName: "Track trip", expirationHandler: {
self.endBackgroundTask()
})
}
func endBackgroundTask() {
UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
In ApplicationDidEnterBackground:在 ApplicationDidEnterBackground 中:
func applicationDidEnterBackground(_ application: UIApplication) {
//Start the background fetch
self.doBackgroundTask()
}
In ApplicationWillEnterForeground:在 ApplicationWillEnterForeground 中:
func applicationWillEnterForeground(_ application: UIApplication) {
if self.backgroundTaskTimer != nil {
self.backgroundTaskTimer.invalidate()
self.backgroundTaskTimer = nil
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.