Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

How to delay execution or scheduled automatic operations in SwiftUI

2022-03-14 | Swift | #Words: 1005 | 中文原版

In the process of developing software, we not only need to perform operations when the user clicks, but sometimes we also need to automatically perform some operations at regular intervals. For example, the most common opening screen advertisement countdown is closed, as well as some animation effects. There are generally two ways to implement these: one is to use a timer, and the other is to use asynchronous operations.

Advantages and Disadvantages

How to use timer Timer

First we need to create a new Timer and use the following method to create it. The last .autoconnect() is used to automatically start the connection timer. We can also use .connect() to manually activate the connection.

let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()

Here are some parameters:

It should be noted that if you are developing on macOS, there will be two more modes: .eventTracking and .modalPanel. .eventTracking is the mode set when tracking events modally, such as a mouse drag loop. .modalPanel is the mode set when waiting for input from a modal panel (such as saving or opening a panel).

Then close and disconnect the Timer as follows:

self.timer.upstream.connect().cancel()

Timer looks complicated, but you don’t need to think too much about using it. Next, let’s talk about how to use Timer after creating it.

In SwiftUI, we can let the view perform some operations when some data changes by using .onReceive(). The specific method is as follows:

.onReceive(timer) { _ in
print("Timer active, add 1 second")
}

Then write a simple timer interface that counts down from 5 and loops again after the countdown:

struct TimerView: View {
     @State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
     @State private var countNum = 5
     var body: some View {
         Text("\(countNum)")
             .onReceive(timer) { input in
                 if countNum > 0{
                     countNum -= 1
                 } else if countNum == 0{
                     countNum = 5
                 }
             }
     }
}

Asynchronous operation DispatchQueue

Next, let’s talk about the asynchronous operation DispatchQueue. This is also very commonly used, especially when you need to load data or do effects or animations. It is very easy to use.

How to use it:

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
     print("The wait is over!")
})

Introduce the parameters:

This is relatively simple, so I won’t introduce it in too much detail.

I hope these will help someone in need~