首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定时器在后台运行时间不超过3分钟

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

Stack Overflow用户
提问于 2018-03-10 12:12:08
回答 1查看 864关注 0票数 1

我在做冥想应用程序。在这个应用程序中,我有一些音乐内容和一些静默冥想部分使用计时器。定时器在前台时工作正常,但在后台只运行3分钟(当设备被锁定或用户按主按钮退出应用程序时)。我正在使用swift4。我试过的是:

代码语言:javascript
复制
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)
}

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-03-10 12:45:31

一般来说,您从操作系统获得有限的时间运行在后台。您可以使用以下方法检查背景时间并对其作出反应:

代码语言:javascript
复制
UIApplication.shared.backgroundTimeRemaining

如果条件良好(设备解锁,电池满.)你通常有160-180秒的时间。

您可以在苹果文献中找到详细信息。

由于您想播放音频,您可以使用“play audio”后台模式来不被OS剪切:

根据您播放音频的方式,配置AudioSession还可以改进一些内容。

编辑:我从你的评论中了解到,你希望你的应用程序每4分钟做一次。我看到的唯一可能就是使用BackgroundFetch特性。不过,这并不能保证固定的间隔。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49208925

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档