How to repeat a task repeatedly after a regular interval in Swift(iOS)?


In this post we will learn how to repeat a task after a regular interval.

In this example we will update a label after a particular interval of time repeatedly.

In iOS we user Timer to achieve this task. Lets get started

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “Timer”

Step 2 − Open Main.storyboard and add a label as shown below.

Step 3 − Attach one @IBOutlet for the bottom label. Name it timerLabel

Step 4 − We will show the seconds since when the app is launched on the label. So, declare two variables in view controller as follows.

var timeLaunched: Int = 0
var timer: Timer?

Step 5 − Add a function that updates the label. We will call this function repeatedly at regular intervals afterwards.

@objc func updateLabel() {
   timerLabel.text = " Time Launched = \(timeLaunched) Seconds "
   timeLaunched += 1
}

As you can see this function increments the time launched and shows it on the label.

Step 6 − Initialize and trigger the timer. In viewDidLoad of ViewController initialize the timer and call the function updateLabel at regular intervals. Here we are triggering the function at every 1 second. You can trigger the function based on your requirement.

override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view, typically from a nib.
   updateLabel()
   timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateLabel)), userInfo: nil, repeats: true)
}

As you can see we have initialized the timer, and set ‘repeats’ to true. This will call the function updateLabel every second.

Launch the app, you can see the label updating every second.

raja
Published on 11-Sep-2019 12:27:55
Advertisements