Return Value 戻り値
A view that runs the specified action asynchronously when the view appears, or restarts the task with the id
value changes.
Availability 有効性
Technology
func task<T>(id value: T, priority: TaskPriority
= .userInitiated, _ action: @escaping () async -> Void
) -> some View
where T : Equatable
A view that runs the specified action asynchronously when the view appears, or restarts the task with the id
value changes.
id
priority
The task priority to use when creating the asynchronous task. The default priority is user
.
action
A closure that SwiftUI calls as an asynchronous task when the view appears. SwiftUI automatically cancels the task if the view disappears before the action completes. If the id
value changes, SwiftUI cancels and restarts the task.
This method behaves like task(priority:
, except that it also cancels and recreates the task when a specified value changes. To detect a change, the modifier tests whether a new value for the id
parameter equals the previous value. For this to work, the value’s type must conform to the Equatable
protocol.
For example, if you define an equatable Server
type that posts custom notifications whenever its state changes — for example, from signed out to signed in — you can use the task modifier to update the contents of a Text
view to reflect the state of the currently selected server:
Text(status ?? "Signed Out")
.task(id: server) {
let sequence = NotificationCenter.default.notifications(
named: .didChangeStatus,
object: server)
for try await notification in sequence {
status = notification.userInfo["status"] as? String
}
}
This example uses the notifications(named:
method to wait indefinitely for an asynchronous sequence of notifications, given by an Async
instance.
Elsewhere, the server defines a custom did
notification:
extension NSNotification.Name {
static var didUpdateStatus: NSNotification.Name {
NSNotification.Name("didUpdateStatus")
}
}
The server then posts a notification of this type whenever its status changes, like after the user signs in:
let notification = Notification(
name: .didUpdateStatus,
object: self,
userInfo: ["status": "Signed In"])
NotificationCenter.default.post(notification)
The task attached to the Text
view gets and displays the status value from the notification’s user information dictionary. When the user chooses a different server, SwiftUI cancels the task and creates a new one, which then starts waiting for notifications from the new server.