How to use the NSTimer in Swift.
- parameter repeats: true -> repeat, false -> no repeat.
- We don't have to call 'timer.fire()' before NSTimer of the method of scheduledTimerWithTimeInterval. Those will fire automatically.
| class SwiftTimer { | |
| var timer: Timer! | |
| let interval: Double = 5 | |
| init() { | |
| } | |
| func startTimer() { | |
| // When declare a timer then the timer will start counting directly. | |
| self.timer = Timer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(action), userInfo: nil, repeats: false) | |
| } | |
| func stopTimer() { | |
| // Stop the timer counting and cancel it. | |
| self.timer?.invalidate() | |
| self.timer = nil | |
| } | |
| func action() { | |
| // Do something you want. | |
| } | |
| } |