Barrows Script 🚀

How do I write dispatchafter GCD in Swift 3 4 and 5

April 18, 2025

How do I write dispatchafter GCD in Swift 3 4 and 5

Mastering asynchronous operations is important for gathering responsive and businesslike iOS apps. 1 of the about communal methods to negociate these operations successful Swift is utilizing Expansive Cardinal Dispatch (GCD), particularly the dispatch_after relation. This relation permits you to agenda duties to tally last a specified clip hold, stopping your chief thread from blocking and guaranteeing a creaseless person education. Whether or not you’re running with Swift three, four, oregon 5, knowing however to leverage dispatch_after efficaciously is indispensable for immoderate iOS developer.

Knowing Expansive Cardinal Dispatch (GCD)

GCD is a almighty application offered by Pome to negociate concurrent duties effectively. It simplifies the procedure of running with aggregate threads and helps optimize exertion show. By using queues and dispatching duties, GCD abstracts distant overmuch of the complexity related with multithreading, permitting builders to direction connected the logic of their codification instead than debased-flat thread direction. GCD is the spine of asynchronous programming successful Swift.

Queues are the bosom of GCD. They negociate the execution of duties, guaranteeing they are carried out successful the accurate command. Location are 2 chief varieties: serial queues execute duties 1 astatine a clip, piece concurrent queues tin execute aggregate duties concurrently. dispatch_after plant by including a project to a specified queue last a fixed hold.

Utilizing GCD and dispatch_after decently tin importantly better your app’s show and responsiveness. Offloading agelong-moving duties to inheritance queues prevents the chief thread from being blocked, which tin pb to UI freezes and a mediocre person education. This is particularly crucial for duties similar web requests, representation processing, and analyzable computations.

Implementing dispatch_after successful Swift

The dispatch_after relation takes 2 chief arguments: a DispatchTime representing the hold and a DispatchQueue specifying the queue connected which the project ought to beryllium executed. The codification artifact to beryllium executed is enclosed inside the dispatch_after relation call.

Present’s a basal illustration of however to usage dispatch_after successful Swift:

DispatchQueue.chief.asyncAfter(deadline: .present() + 2) { // Codification to beryllium executed last 2 seconds mark("This volition tally last a 2 2nd hold") } 

This codification snippet schedules a project to beryllium executed connected the chief queue last a hold of 2 seconds. The .present() + 2 creates a DispatchTime representing 2 seconds from the actual clip. The codification inside the closure volition beryllium executed last the specified hold.

For inheritance execution, usage a antithetic queue, similar a planetary inheritance queue:

DispatchQueue.planetary(qos: .inheritance).asyncAfter(deadline: .present() + 2) { // Codification to beryllium executed last 2 seconds connected a inheritance queue mark("This volition tally connected a inheritance queue last 2 seconds") DispatchQueue.chief.async { // Replace UI connected chief thread if wanted } } 

Selecting the Correct DispatchQueue

Choosing the due DispatchQueue is important for the effectual usage of dispatch_after. The chief queue is liable for dealing with UI updates and ought to beryllium utilized for duties that straight impact the person interface. Nevertheless, for agelong-moving duties, utilizing a inheritance queue is indispensable to forestall UI blocking. Selecting the accurate choice of work (QoS) for your inheritance queue helps the scheme prioritize duties and optimize assets allocation.

Location are respective QoS courses disposable, together with .userInteractive, .userInitiated, .inferior, and .inheritance. All people represents a antithetic flat of precedence, with .userInteractive being the highest and .inheritance being the lowest. Deciding on the due QoS ensures that duties are executed effectively and successful a well timed mode.

See the quality of the project once selecting a queue. Duties that necessitate contiguous execution and straight contact the person education ought to beryllium positioned connected the chief queue oregon a advanced-precedence queue. Duties that tin beryllium carried out successful the inheritance, specified arsenic web requests oregon information processing, ought to beryllium positioned connected a less-precedence queue.

Communal Usage Instances and Champion Practices

dispatch_after is extremely versatile and tin beryllium utilized successful assorted situations. 1 communal usage lawsuit is delaying the execution of codification to make animations oregon timed occasions. For case, you mightiness usage it to show a invited communication last a person logs successful oregon to fell a loading indicator last a definite play. Different communal usage lawsuit is performing inheritance duties last a hold, specified arsenic fetching information from a server oregon processing photographs.

  • Delayed UI Updates: Usage dispatch_after to replace the person interface last a circumstantial hold, specified arsenic displaying a communication oregon animating an component.
  • Inheritance Duties: Execute clip-consuming operations successful the inheritance utilizing a inheritance queue to debar blocking the chief thread.

Once utilizing dispatch_after, it’s crucial to see possible representation leaks, particularly once capturing same successful closures. Utilizing anemic same tin aid forestall these points. Besides, guarantee that the hold you specify is due for the project. Overly agelong delays tin pb to pointless ready, piece overly abbreviated delays tin overwhelm the scheme.

  1. Place the project you privation to hold.
  2. Take the due DispatchQueue (chief oregon inheritance).
  3. Find the desired hold.
  4. Instrumentality the dispatch_after relation with the accurate parameters.

Seat much precocious GCD ideas successful this article: Precocious GCD Strategies

Infographic Placeholder: [Insert infographic illustrating the antithetic queues and QoS courses]

FAQ

Q: What is the quality betwixt dispatch_after and DispatchQueue.async?

A: dispatch_after schedules a project to tally last a circumstantial hold, piece DispatchQueue.async schedules a project to tally arsenic shortly arsenic imaginable with out a hold.

Leveraging the powerfulness of Expansive Cardinal Dispatch and the dispatch_after relation is cardinal for creating responsive and advanced-performing iOS purposes. By knowing however to take the correct queue, negociate delays efficaciously, and travel champion practices, you tin guarantee creaseless person experiences and optimize your app’s general ratio. Research additional sources connected Pome’s developer documentation and on-line tutorials to deepen your knowing and maestro asynchronous programming successful Swift. Statesman optimizing your apps present with the strategies outlined present.

Additional speechmaking: Pome’s Dispatch Documentation, Ray Wenderlich GCD Tutorial, Hacking with Swift - GCD.

Question & Answer :
Successful Swift 2, I was capable to usage dispatch_after to hold an act utilizing expansive cardinal dispatch:

var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(zero.1 * Treble(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { // your relation present }) 

However this nary longer appears to compile since Swift three. What is the most well-liked manner to compose this successful contemporary Swift?

The syntax is merely:

// to tally thing successful zero.1 seconds DispatchQueue.chief.asyncAfter(deadline: .present() + zero.1) { // your codification present } 

Line, the supra syntax of including seconds arsenic a Treble appears to beryllium a origin of disorder (esp since we had been accustomed to including nsec). That “adhd seconds arsenic Treble” syntax plant due to the fact that deadline is a DispatchTime and, down the scenes, location is a + function that volition return a Treble and adhd that galore seconds to the DispatchTime:

national func +(clip: DispatchTime, seconds: Treble) -> DispatchTime 

However, if you truly privation to adhd an integer figure of msec, μs, oregon nsec to the DispatchTime, you tin besides adhd a DispatchTimeInterval to a DispatchTime. That means you tin bash:

DispatchQueue.chief.asyncAfter(deadline: .present() + .milliseconds(500)) { // 500 msec, i.e. zero.5 seconds … } DispatchQueue.chief.asyncAfter(deadline: .present() + .microseconds(1_000_000)) { // 1m microseconds, i.e. 1 2nd … } DispatchQueue.chief.asyncAfter(deadline: .present() + .nanoseconds(1_500_000_000)) { // 1.5b nanoseconds, i.e. 1.5 seconds … } 

These each seamlessly activity due to the fact that of this abstracted overload technique for the + function successful the DispatchTime people.

national func +(clip: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime 

It was requested however 1 goes astir canceling a dispatched project. To bash this, usage DispatchWorkItem. For illustration, this begins a project that volition occurrence successful 5 seconds, oregon if the position controller is dismissed and deallocated, its deinit volition cancel the project:

people ViewController: UIViewController { backstage var point: DispatchWorkItem? override func viewDidLoad() { ace.viewDidLoad() point = DispatchWorkItem { [anemic same] successful same?.doSomething() same?.point = nil } DispatchQueue.chief.asyncAfter(deadline: .present() + 5, execute: point!) } deinit { point?.cancel() } func doSomething() { … } } 

Line the usage of the [anemic same] seizure database successful the DispatchWorkItem. This is indispensable to debar a beardown mention rhythm. Besides line that this does not bash a preemptive cancelation, however instead conscionable stops the project from beginning if it hasn’t already. However if it has already began by the clip it encounters the cancel() call, the artifact volition decorativeness its execution (until you’re manually checking isCancelled wrong the artifact).


Swift concurrency

Piece the first motion was astir the aged GCD dispatch_after vs. the newer asyncAfter API, this raises the motion of however to accomplish the aforesaid behaviour successful the newer Swift concurrency and its async-await. Arsenic of iOS sixteen and macOS thirteen we would like Project.slumber(for:):

attempt await Project.slumber(for: .seconds(2)) // 2 seconds … 

Oregon

attempt await Project.slumber(for: .milliseconds(200)) // zero.2 seconds … 

Oregon if we demand to activity backmost to iOS thirteen and macOS 10.15, we would usage Project.slumber(nanoseconds:) alternatively.

And to activity cancelation, prevention a Project:

people ViewController: UIViewController { backstage var project: Project<Void, Mistake>? override func viewDidAppear(_ animated: Bool) { ace.viewDidAppear(animated) project = Project { attempt await Project.slumber(for: .seconds(5)) await doSomething() } } override func viewDidDisappear(_ animated: Bool) { ace.viewDidDisappear(animated) project?.cancel() } func doSomething() async { … } } 

Oregon successful SwiftUI, we mightiness usage the .project {…} position modifier, which “volition mechanically cancel the project astatine any component last the position disappears earlier the act completes.” We bash not equal demand to prevention the Project to manually cancel future.

We ought to acknowledge that earlier we had Swift concurrency, calling immoderate slumber relation utilized to beryllium an anti-form, 1 that we would studiously debar, due to the fact that it would artifact the actual thread. That was a capital mistake once performed from the chief thread, however equal was problematic once utilized successful inheritance threads arsenic the GCD person thread excavation is truthful constricted. However the fresh Project.slumber features bash not artifact the actual thread, and are so harmless to usage from immoderate histrion (together with the chief histrion).