1

I'm not sure why but every time I run my application, my timer will not call the update function. I have tried everything: using #selector, adding a colon at the end of update, nothing is working. I have added a print statement inside my update to make sure that it reaches there, and the print statement never prints! I'm not sure why it isn't being called.... Help! P.S. I know selected is indeed one of the options in the if statement, I had a print statement for that and it's working.

 if (selected == "05 seconds") { count = 5 timer = Timer(timeInterval: 1.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } else if (selected == "10 seconds") { count = 10 timer = Timer(timeInterval: 1.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } else if (selected == "20 seconds") { count = 20 timer = Timer(timeInterval: 1.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } else if (selected == "30 seconds") { print("I'm here!") count = 30 timer = Timer(timeInterval: 1.0, target: self, selector: Selector("update"), userInfo: nil, repeats: true) } else if (selected == "Single Shot") { SendButton.isHidden = false countDownLabel.isHidden = true } } func update() { print("Now I'm in update!") count = count - 1; countDownLabel.text = String(count) } 
1
  • 1
    Also, the correct way to use selectors in Swift 3 is #selector(update(_:)). That way you can pass the sender to the function. Commented Nov 19, 2016 at 16:12

1 Answer 1

8

The timer does not work, because the method you are using requires that the timer is explicitly added to the runloop.

Use the API which adds the timer implicitly to the runloop.

DispatchQueue.main.async { timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true) } 

PS: The #selector syntax is preferable because it checks the existence of the action method at compile time.

Sign up to request clarification or add additional context in comments.

3 Comments

I have done this exactly but it still does not call my update function... Know why?
There could be many reasons. Does the function match the selector? Is there a strong reference to the timer. Is the target in the same class as the selector?
In my case I was invoking Timer.scheduledTimer not from main thread. It seems you need to call Timer.scheduledTimer from main thread.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.