Akeno Akeno - 1 year ago 131
iOS Question

NSTimer scheduledTimerWithTimeInterval - not calling funciton

I want to run a timer in the background. So I created a singleton.

The problem is that after the set 5.0 seconds, it does not call the function

. XCode proposes to add
in front of the function (like this:
@Objc func timeEnded() {...
) to solve some problem (I don't get what, though). But it still doesn't call that function. Any ideas?

class TimerService {
static let instance = TimerService()
var internalTimer: NSTimer?

func startTimer() {
guard internalTimer != nil else {
return print("timer already started")
internalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(TimerService.timeEnded), userInfo: nil, repeats: false)

func timeEnded() {
//NSNotificationCenter.defaultCenter().postNotificationName("timerEnded", object: nil)
print("timer Ended")


Answer Source

You never actually start the timer because your startTimer() function will always return before reaching the line where you actually start the timer.

In your guard statement you only continue the execution of the function if internalTimer != nil but you set the timer after that statement. Thus, your internalTimer will always be nil.