Ios 使NSTimer在物理设备上后台运行
我有一个我制作的计时器应用程序 当我在模拟器上的iPhoneX上运行它时,计时器会在后台正常运行,但当我在我的物理设备(iPad Pro)上测试它时,它不会在后台运行Ios 使NSTimer在物理设备上后台运行,ios,iphone,swift,xcode,ipad,Ios,Iphone,Swift,Xcode,Ipad,我有一个我制作的计时器应用程序 当我在模拟器上的iPhoneX上运行它时,计时器会在后台正常运行,但当我在我的物理设备(iPad Pro)上测试它时,它不会在后台运行 当我在后台说,我的意思是当你按下位于设备顶部(iPad)/侧面(iPhone)的off按钮时,屏幕变黑 这是模拟器的一个小故障,还是我不知道的问题,或者我的应用程序有什么需要更改的地方,以使其在物理设备的后台工作 谢谢 背景: 停止正常计时器 启动新的backgroundTaskTimer 在前景中: 停止背景任务计时器 启动
- 当我在后台说,我的意思是当你按下位于设备顶部(iPad)/侧面(iPhone)的off按钮时,屏幕变黑
请搜索。这已经被报道过很多次了。您需要提供更多关于“它不在后台运行”的信息。你希望它在后台做什么?ryantxr我的意思是,我想要一个间隔为1的时间在后台继续运行,这样当计时器达到某个时间时,音频可以运行。
var backgroundUpdateTask: UIBackgroundTaskIdentifier!
var backgroundTaskTimer:Timer! = Timer()
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
}
func applicationDidEnterBackground(_ application: UIApplication) {
//Start the background fetch
self.doBackgroundTask()
}
func applicationWillEnterForeground(_ application: UIApplication) {
if self.backgroundTaskTimer != nil {
self.backgroundTaskTimer.invalidate()
self.backgroundTaskTimer = nil
}
}