2

I'm writing a time tracking app and it works perfectly in the simulator. I press start at 9:00, lock the screen, come back at 9:05 and the timer adjusts to 5 minutes. However, on my actual device nothing happens in the background. What's causing this?
Here is my code for background mode. I also have checked background mode on in the target capabilities.

When entering background mode, find the date to calculate how long it was in background.

func appGoesIntoBackground() {
    if isActivityPaused == false {
        quitDate = NSDate()
    }
}

Once loaded from the background, calculate how long it was in background and display that.

  func appLoadedFromBackground() {
    if isActivityPaused == false {
        let passedSecondsTillInactive = 
  NSDate().timeIntervalSinceDate(quitDate!)
        passedSeconds += Int(passedSecondsTillInactive)
    }
   }

Save to history. It doesn't work in simulator if I cut out startDate = nil and choosenActivity = nil.

func saveActivityToHistory() {
    CoreDataHandler.sharedInstance.saveHistory(choosenActivity!.name!, 
startDate: startDate!, endDate: NSDate(), duration: passedSeconds)
    startDate = nil
    choosenActivity = nil
    passedSeconds = 0
    loadCoreDataEntities()
}
4

2 回答 2

1

8.0 和 11.0 Beta 2 之间的 iOS Simualtor 运行时无法暂停后台任务。从 iOS 11.0 Beta 3 Simulator(它是 Xcode 9.0 Beta 3 的一部分)开始,此问题已得到解决。应适当暂停后台应用程序以更好地匹配设备行为。

于 2017-07-13T00:09:12.440 回答
1

在这种情况下,我没有看到任何背景模式的理由。我建议您以其他方式将 quitDate 持久化到 userDefaults、plist 文件或 Core Data。这样,应用程序进入后台后发生的事情无关紧要,也无关紧要。您从唤醒时的持久数据中检索退出日期并按预期继续。

于 2016-07-20T22:32:07.007 回答