How to use Timer in Swift

Issue #212

Pre iOS 10

1
2
3
4
5
6
7
8
9
10
func schedule() {
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 20, target: self,
selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: false)
}
}

@objc private func timerDidFire(timer: Timer) {
print(timer)
}

iOS 10+

1
2
3
4
5
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in
print(timer)
}
}

Note that

  • It needs to be on the main queue
  • Callback function can be public, private, …
  • Callback function needs to be @objc

Original answer https://stackoverflow.com/a/42273141/1418457

Comments