Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a delay in Swift?

I want to pause my app at a certain in point. In other words, I want my app to execute the code, but then at a certain point, pause for 4 seconds, and then continue on with the rest of the code. How can I do this?

I am using Swift.

like image 969
Schuey999 Avatar asked Dec 17 '14 02:12

Schuey999


People also ask

How do I create a delay in Swift?

To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.

What is a task in Swift?

Tasks in Swift are part of the concurrency framework introduced at WWDC 2021. A task allows us to create a concurrent environment from a non-concurrent method, calling methods using async/await. When working with tasks for the first time, you might recognize familiarities between dispatch queues and tasks.


1 Answers

Using a dispatch_after block is in most cases better than using sleep(time) as the thread on which the sleep is performed is blocked from doing other work. when using dispatch_after the thread which is worked on does not get blocked so it can do other work in the meantime.
If you are working on the main thread of your application, using sleep(time) is bad for the user experience of your app as the UI is unresponsive during that time.

Dispatch after schedules the execution of a block of code instead of freezing the thread:

Swift ≥ 3.0

let seconds = 4.0 DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {     // Put your code which should be executed with a delay here } 

Swift ≥ 5.5 in an async context:

func foo() async {     await Task.sleep(UInt64(seconds * Double(NSEC_PER_SEC)))     // Put your code which should be executed with a delay here } 

Swift < 3.0

let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) {     // Put your code which should be executed with a delay here } 
like image 151
Palle Avatar answered Oct 11 '22 10:10

Palle