How to execute a task repeatedly after fixed time intervals in iOS

iOSApps/ApplicationsMobile Development

Apple has predefined class Timer, that fires after a certain time interval has elapsed, sending a specified message to a target object.

To read more about the Timer class you can check official apple documentation here

https://developer.apple.com/documentation/foundation/timer

To execute the task repeatedly after fixed interval of time we are going to use timer class. We are going to develop a sample application where the application prints hello Tutorials Point after every 5 seconds.

So let’s get started,

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

Step 2  − Open ViewController.swift and write one method doSomething() below ViewDidLoad(). Copy paste below code in your doSomething method().

private func doSomething() {
   let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
      selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
}

Step 3: Implement/Create hello (selector ) as show below, and call doSomething() within ViewDidLoad().

@objc func hello() {
   print("hello")
}

Your final code should look like below

import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
   override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      self.doSomething()
   }
   private func doSomething() {
      let timer = Timer.scheduledTimer(timeInterval: 5.0, target: self,
      selector: #selector(ViewController.hello), userInfo: nil, repeats: true)
   }
   @objc func hello() {
      print("hello")
   }
}

We’re done run your application and check out the output in console, you’ll see “hello” printing after time interval of 5 seconds.

raja
Published on 09-May-2019 07:45:11
Advertisements