我正在开发冥想应用程序。在这个应用程序中,我有一些音乐内容和一些使用计时器的静默冥想部分。计时器在前台时工作正常,但在后台仅运行 3 分钟(当设备锁定或用户按主页按钮退出应用程序时)。我正在使用 swift4。我试过的:
var timer: Timer!
var timeCounter : Int!
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
var backgroundTask = BackgroundTask()
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
backgroundTask.startBackgroundTask()
DispatchQueue.global(qos: .background).async {
let currentRunLoop = RunLoop.current
let timeInterval = 1.0
self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)
self.timer.tolerance = timeInterval * 0.1
currentRunLoop.add(self.timer, forMode: .commonModes)
currentRunLoop.run()
}
}
}
@objc func updateTimer () {
timeCounter = timeCounter - 1
let minutes = Int(timeCounter) / 60 % 60
let seconds = Int(timeCounter) % 60
print("timeCounter", timeCounter)
if (timeCounter == 0){
if self.timer != nil {
self.timer?.invalidate()
self.timer = nil
player.play()
}
}
timeLabel.fadeTransition(0.4)
timeLabel.text = String(format: "%02i:%02i",minutes,seconds)
}
提前致谢。
最佳答案
通常,操作系统在后台运行的时间有限。您可以使用以下方法检查剩余的后台时间并使用react:
UIApplication.shared.backgroundTimeRemaining
如果情况良好(设备已解锁、电池已充满...),您通常需要大约 160-180 秒。
您可以在 Apples documentation 中找到详细信息.
如果你想播放音频,你可以使用“播放音频”后台模式不被操作系统切断:
取决于您播放音频的方式,configuring the AudioSession也可能会有所改善。
编辑: 我现在从您的评论中了解到,您希望您的应用每 4 分钟执行一次操作。我看到的唯一可能性是使用 BackgroundFetch特征。但这并不能保证固定的间隔。
关于ios - 计时器在后台运行不超过 3 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49208925/