计时器在后台运行时间不超过3分钟

时间:2018-03-10 12:12:09

标签: ios swift nstimer background-process

我正在研究冥想应用。在这个应用程序中我有一些音乐内容和一些使用计时器的沉默冥想部分。定时器在前台工作正常但在后台运行仅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)
}

先谢谢。

1 个答案:

答案 0 :(得分:2)

通常,您从操作系统到后台运行的时间有限。您可以使用以下方法检查并对剩余的背景时间作出反应:

UIApplication.shared.backgroundTimeRemaining

如果情况良好(设备已解锁,电池电量充足......),通常会持续160-180秒。

您可以在Apples documentation中找到详细信息。

由于您想播放音频,您可以使用“播放音频”背景模式,以免被操作系统切断:

Capabilities

根据您播放音频的方式,configuring the AudioSession也可能会有所改善。

编辑: 我现在从您的评论中了解到,您希望您的应用每隔4分钟执行一次操作。我看到的唯一可能性是使用BackgroundFetch功能。但这并不能保证固定的间隔。