【SwiftUI】task の id を使って処理を何度も繰り返す

この id を書き換えることで task のクロージャ内の処理を繰り返すことができるんですね !

onAppear と同様に初回だけだと思ってましたわ。


func task<T>(
    id value: T,
    priority: TaskPriority = .userInitiated,
    _ action: @escaping () async -> Void
) -> some View where T : Equatable

id
The value to observe for changes. The value must conform to the Equatable protocol.

👉 task(id:priority:_:) | Apple Developer Documentation hatena-bookmark

 

■ やってみる

公開されている無料現在時刻取得のAPIを使います。


# curl "http://worldtimeapi.org/api/timezone/Asia/Tokyo"

{
  "abbreviation": "JST",
  "client_ip": "2675:6780:4e0:3200:a181:c317:3902:c121",
  "datetime": "2024-03-26T22:10:13.824894+09:00",
  "day_of_week": 2,
  "day_of_year": 86,
  "dst": false,
  "dst_from": null,
  "dst_offset": 0,
  "dst_until": null,
  "raw_offset": 32400,
  "timezone": "Asia/Tokyo",
  "unixtime": 1711458613,
  "utc_datetime": "2024-03-26T13:10:13.824894+00:00",
  "utc_offset": "+09:00",
  "week_number": 13
}

👉 World Time API: Simple JSON/plain-text API to obtain the current time in, and related data about, a timezone. hatena-bookmark

クライアント側はシンプルな実装にしておきます。


let url = URL(string: "https://worldtimeapi.org/api/timezone/Asia/Tokyo.txt")!
var lines: [String] = []
for try await line in url.lines {
  lines.append(line)
}
print(String(lines[2].components(separatedBy: "T")[1]))

// 22:10:13.824894+09:00

👉 【SwiftUI】シンプルに HTTPリクエスト でお天気情報取得 hatena-bookmark

task (id:) を使っておいて、ボタンで id を更新させます。

 

■ まとめ

「id」って便利な使えるやつなんですね !

👉 【SwiftUI】View の 強制再描画 hatena-bookmark