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 https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter

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

func functionOne() {
   let delayTime = DispatchTime.now() + 3.0
   print("one")
   DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {
      hello()
   })
}
func hello() {
   print("text")
} 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() {
      super.viewDidLoad()
      print("one")
      Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false)
   }
   @objc func hello() {
      print("text")
   }
}

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

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