mefahimrahman
mefahimrahman

Reputation: 349

timer gets called after coming back from minimized state iOS

I build a real time clock after fetching current location and then shows current time from api response - I'm using these function to display current time.

func getCurrentTime() {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.currentTimeAfterFetchedTime), userInfo: nil, repeats: true)
}

@objc func currentTimeAfterFetchedTime(currentTime : Int) {
    print("Timer Function gets Called \(Date())")
    let formatter = DateFormatter()
    formatter.dateFormat = "MMM d, h:mm:ss a"
    DispatchQueue.main.async {
        self.presentDayDateNTime.text = formatter.string(from: Date(timeIntervalSince1970: TimeInterval(self.dynamicCurrentDateNTime)))
        self.dynamicCurrentDateNTime += 1
    }
}

Now I want to refetch api and show real time if user come back after minimized state. So I added this Notification observer to check if the app comes back from minimized state or not -

NotificationCenter.default.addObserver(self, selector: #selector(applicationComesInTheForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

In my viewDidLoad() and also define this to fetch location and call api again-

@objc func applicationComesInTheForeground() {
    print("Called")
    self.spinner.startAnimating()
    fetchCurrentLocation()
}

My app works fine when starts first time but when it coming back from minimize state the currentTimeAfterFetchedTime gets called doubled in a seconds and my clock gets fast enough to count 1 minute in just 30 seconds.

I'm calling currentTimeAfterFetchedTime function from completionhandler of api call-

DispatchQueue.main.async {
            print("In Dispathch",self.currentDayData)
            
            // MARK: - Dynamic time representation afetr fetching data from API
            self.dynamicCurrentDateNTime = self.currentDayData.dt
            self.getCurrentTime()
}

So, My question is why my timer function gets called double in a seconds?

Upvotes: 1

Views: 89

Answers (2)

BharathRao
BharathRao

Reputation: 2056

Add the following observer and invalidate the timer whenever the app goes to background or inactive state.

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillBecomeInactive), name: UIApplication.willResignActiveNotification, object: nil)
@objc func applicationWillBecomeInactive() {
    print("application inactive")
    timer.invalidate()
}

Whenever the App becomes active you can start the timer (as done by you)

Upvotes: 1

erim kurt
erim kurt

Reputation: 91

You should reset the old timer in getCurrentTime() before the start it.

timer.invalidate()

Upvotes: 1

Related Questions