How can one use Date to get elapsed time between when the app is in the foreground and background

Ok, so this is what I have right now:


var beginDate = Date()
var endDate = Date()

override func viewDidAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(appWentInBackground), name: .UIApplicationDidEnterBackground, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)
        
    }


@objc func appWentInBackground(){
        beginDate = Date()
        
    }
    
@objc func appWillEnterForeground() {
        endDate = Date()
        let secondsPassedInBackground = endDate.timeIntervalSince(beginDate) // Double
        let updateBrTime = intBrSeconds - Int(secondsPassedInBackground) // Updated Break Time after user returns to the app aka foreground
        breakSession.text = brTimeString(bTime: TimeInterval(updateBrTime))
    }


FYI: The value of intBrSeconds is inputted in by the user.


Problem: The problem I have is that for some reason, the "time" in the label increases somehow even though I am subtracting the elapsed time (secondsPassedInBackground) from intBrSeconds to get the updated time in updateBrTime. For example, after I go to the background and come back the appropriate amount of seconds will be subtracted the first couple time or so. But then after say I do go to the background and comeback for the 4th time, the label will display an increased time than before, even thought I am doing intBrSeconds - Int(secondsPassedInBackground). Can anyone help?

I can’t see anything obviously broken with your code. My recommendation is that you set a breakpoint on line 18 — which is after the last time critical point in your code — and then step through the code looking at the various values in play.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
How can one use Date to get elapsed time between when the app is in the foreground and background
 
 
Q