iOS Timer Tutorial in Swift

On February 28, 2016, in Swift, by James Liu

Timer is a very common method to perform a schedule task within a period of time. We can execute the timer once or repeatedly. In this tutorial, I will show you how to use iOS timer in Swift. Once you finish this tutorial, you will understand how to create a iOS timer in Swift and execute a task after a certain time interval.

In iOS, timer is working tightly with run loop. The timer is triggered by run loop. When we create a timer, we need to add this timer to a run loop manually or automatically. Each timer can only be registered in one run loop at a time, although it can be added to multiple run loop modes within that run loop. For applications built using Application Kit or UIKit, the application object runs the main thread’s run loop.

The timer is not accurate. It depends on the run loop modes to which the timer has been added. When the run loop is running and able to monitor that the timer’s firing time has passed, then the timer will fire. Otherwise the timer will not fire until the run loop checks the timer.

In this tutorial, I will create a repeating timer to update a progress bar in very 1 millisecond for 1000 timers. The whole example will be written in Swift.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var timerLabel: UILabel!
    var timer: NSTimer!;
    @IBOutlet weak var timerProgress: UIProgressView!
    var counter: Int = 0;
    var total: Int = 1000;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector:"timerFunction:", userInfo: nil, repeats: true);
        timerProgress.setProgress(0.00, animated: false);
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func timerFunction(atimer:NSTimer) {
        counter++;
        timerLabel.text = NSString(format:"%d", counter) as String;
        timerProgress.setProgress(Float(counter)/Float(total), animated: false);
        NSLog("%d: %.2f", counter, Float(counter)/Float(total));
        
        if(counter == total) {
            timer.invalidate();
        }
    }
}

Now, let’s check the result in the iOS simulator:

Download Source Code for Free

You can download this source code for free.

 

Leave a Reply

Weboy

Premium WordPress Themes