phapli
phapli

Reputation: 647

Swift timer in background

I create a background task in iOS by trigger from a geofence. In this background I start a timer to count down time to timeout this task. However, this timer work incorrectly, maybe pause after 10s and resume whenever I bing my app to foreground.

I need help to make this timer work correctly in 10 minute. This is my code

@objc func timeoutChecking(_ timer: Timer) {
    print("time \(self.currentTime)")
    if self.currentTime != TIME_SEARCH {
        self.currentTime += 1
    }
    else {
        // Time out
        self.stopChecking()
    }
}

Upvotes: 1

Views: 2246

Answers (1)

Harsh Pipaliya
Harsh Pipaliya

Reputation: 2431

It's not possible to run timer continuously in the background after a couple seconds apple may discard the timer.

You can do one thing, take one global variable add set current time in applicationDidEnterBackground, and applicationWillEnterForeground check in this method take current system time and stored previous time compare both times and get a difference between them and check is,

if self.currentTime != TIME_SEARCH {
        self.currentTime += 1
    }
    else {
        // Time out
        self.stopChecking()
}

You have to check here like if self.currentTime > TIME_SEARCH or if self.currentTime < TIME_SEARCH so you can get perfect result. :)

Upvotes: 2

Related Questions