Osama Naeem
Osama Naeem

Reputation: 1954

Timer disrupts when notification center is pulled down in iOS 12

So I am creating an app that has countdown timer. When the app quits I am using observers to know if the app is in background. If it is, I invalidate the timer and store the quit time in userDefaults. Then when the app comes back to foreground, I create a new timer and calculate the time that the app has been in background and subtract it from the total duration in order to get the elapsed time. When app goes to the background, I am storing the time in UserDefaults:

 @objc func applicationDidEnterBackground() {
    let defaults = UserDefaults.standard
    let quitTime = Date()
    defaults.set(quitTime, forKey: "quitTimeKey") //Storing the time of quit in UserDefaults
    timer?.invalidate()

}

Then I create a new instance of timer when app enters foreground:

@objc func appEntersForeground() {
    calculateTimeLeft()
    if (timer == nil)
    {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleCountdown), userInfo: nil, repeats: true)
    }

}

Then I check the elapsed time:

func checkElapsedTime() -> Double {
    let currentTime = Date()
    let appQuitTime = UserDefaults.standard.object(forKey: "quitTimeKey") as? Date ?? Date.distantFuture
    let elapsedTime = currentTime.timeIntervalSince(appQuitTime)

    return elapsedTime
}

I am also printing the time difference:

let timeDifference = checkElapsedTime()
print("timeDifference = \(timeDifference)")

Question: However, here is an issue. When I am using the app and I slide the notification center down and back up for not even a second, I get a timeDifference reading of few thousand seconds.

What could be the reason here? Is this iOS 12 bug? This only happens when I pull the notification center down when I am in the app.

Upvotes: 0

Views: 91

Answers (1)

Osama Naeem
Osama Naeem

Reputation: 1954

Alright so I got it working. Basically when you are sliding down the notification center, you are calling applicationWillResignActive. So instead of calling applicationDidEnterBackground, I used applicationWillResignActive for the notification and it started working all fine!

Upvotes: 1

Related Questions