How to call a method after a delay in Swift(iOS)?

iOSApps/ApplicationsMobile Development

In this post, we will be seeing how you can delay a method call using Swift. Here we will be seeing how you can achieve the same in two ways,

So let’s get started,

We will be seeing both the example in Playground,

Step 1 − Open Xcode → New Playground.

In the first approach, we will be using asyncAfter(deadline: execute:) instance method, which Schedules a work item for execution at the specified time and returns immediately.

You can read more about it here

Step 2 − Copy the below code in Playground and run,

func functionOne() {
   let delayTime = + 3.0
   DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
func hello() {
} functionOne()

Here we are creating one function functionOne, where first we are declaring delay time which is 3 Seconds. Then we are using asyncAfter where we are giving the delay time as a parameter and asking to execute hello() function after 3 seconds.

If we run the above program first “one” prints then after 3 seconds “text” prints.

In the second approach, we are going to use NSTimer,

You can copy the below code in your Xcode→Single View application

class ViewController: UIViewController {
   override func viewDidLoad() {
      Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false)
   @objc func hello() {

Run the application, you will see the same output, one is printed and after 3 seconds text is printed.

Published on 23-Oct-2019 08:40:00