Search code examples
iosiphoneswiftbackground-mode

iOS app works in background mode in simulator but not in device?


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()
}

Solution

  • iOS Simualtor runtimes between 8.0 and 11.0 Beta 2 were unable to suspend tasks that were backgrounded. As of iOS 11.0 Beta 3 Simulator (which is part of Xcode 9.0 Beta 3), this has been addressed. Apps that are backgrounded should be properly suspended to better match device behavior.