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()
}
Sammy
  • 79
  • 6

2 Answers2

1

I don't see any reason for background mode in this case. I suggest you persist quitDate some other way, to userDefaults, a plist file or Core Data. This way it does not matter what happens after app goes to background, nor does it matter how long. You retrieve the quit date from the persisted data on wake and proceed as intended.

Dean Davids
  • 4,174
  • 2
  • 30
  • 44
  • That's already what I'm doing. Upon exiting the app, it takes the time of the exit. Upon entering, it calculates the time it was in background and updates the label. My main concern is why it isn't working on my device even though it works on the simulator. I added the background mode as I saw it as a solution to a similar question but nothing really happens during the background mode. – Sammy Jul 20 '16 at 23:14
  • I am guessing that you are storing the backgrounded time in and iVar (quitDate). That variable will not persist once the app is killed. My suggestion was to persist the value of quitDate some other way. Save to Core Data or NSUserDefaults standardUserdefaults. – Dean Davids Jul 23 '16 at 20:00
1

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.

Jeremy Huddleston Sequoia
  • 22,938
  • 5
  • 78
  • 86