view/app关闭后如何保持定时器运行?

How to keep the timer running after the view/app is closed?

我知道有很多与我相关的问题,但我就是不知道在我的情况下该怎么做。

这是一种 "open chest" 类型的游戏。它有一个计时器,一旦它达到零,用户就可以继续下一个 ViewController(这是 ThirdViewcontroller,下一个是 FourthViewController)

我还有 "back" 按钮,可以让您转到第一个ViewController,在那里您可以继续做其他与游戏相关的事情,但您也可以从那里转到第二个ViewController 检查剩余时间。

但每次我这样做时,计时器都会重置,我怎样才能保持它 运行?当用户去其他与游戏相关的东西时?以及如何在应用程序关闭后保留它运行?

剩余的秒数取决于从秒发送的变量ViewController

这是我目前所做的

class StudioWaitingViewController: UIViewController {

   var gameTimer = Timer()
   var studioTime = StudioTime()

   var secondsPassed : Double = 0 
   var timeNeededToRecord : Double = 0 
   var currentTime : Double = 0 
   var percentageOfBar = 0
   var countdown = 0 

override func viewDidLoad() {
       super.viewDidLoad()

       seeResultsButton.isHidden = true
       firstArtistWaitBar.transform = firstArtistWaitBar.transform.scaledBy(x: 1, y: 20)
       firstArtistWaitBar.progress = 0
       firstArtistWaitHour.text = String(format:"%.f", "\(timeNeededToRecord)s")


      gameTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateFirstArtist), userInfo: nil, repeats: true)

       countdown = Int(timeNeededToRecord)


   }

@objc func updateFirstArtist() {

       // if todo
       if secondsPassed < timeNeededToRecord {

           currentTime = secondsPassed / timeNeededToRecord
           secondsPassed += 1
           percentageOfBar = Int(currentTime * 100)
           firstArtistWaitPercentage.text = "\(percentageOfBar)%"


           firstArtistWaitHour.text = "\(countdown)s"
           countdown -= 1



           print(countdown)

           DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
               self.firstArtistWaitBar.setProgress( Float(self.currentTime) , animated: false)
               // 10-second animation changing from 100% to 0%
               UIView.animate(withDuration: 1.5, delay: 0, options: [], animations: { [unowned self] in
                   self.firstArtistWaitBar.layoutIfNeeded()
               })                                                 }



       } else if secondsPassed == timeNeededToRecord {

           firstArtistWaitPercentage.text = "Done!"
           firstArtistWaitBar.setProgress(1, animated: false)
           gameTimer.invalidate()

           firstArtistWaitHour.text = "Done!"

           UIView.animate(withDuration: 1.5, delay: 0, options: [], animations: { [unowned self] in
               self.firstArtistWaitBar.layoutIfNeeded()
           })

           seeResultsButton.isHidden = false
           gameTimer.invalidate()
       }
       // if todo
   }

无论如何,我在编码方面还是很新,如果你看到我可以改进我的代码,请说

要在后台启用计时器功能 运行,您可以在应用程序目标上的签名和功能上的后台模式上标记 Audio, AirPlay, and Picture in Picture 选项。

现在,这仅在应用程序处于后台(未关闭)时有效,当您的应用程序关闭时无法执行任何任务。解决方法是存储上次打开应用程序的时间 date/time 并进行适当的计算。

可以详细说明后台执行。