Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Created November 30, 2023 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brownsoo/413366f7d9958633080073a494bfb407 to your computer and use it in GitHub Desktop.
Save brownsoo/413366f7d9958633080073a494bfb407 to your computer and use it in GitHub Desktop.
SwiftUI 예시 - id 변경으로 Task가 재실행됨
//
// TaskWithIdView.swift
// SwiftUITaskWorkout
//
//
// Created by Paul Hudson.
// https://twostraws.gumroad.com/l/concurrency
import SwiftUI
struct Message: Decodable, Identifiable {
let id: Int
let from: String
let text: String
}
struct TaskWithIdView: View {
@State private var messages = [Message]()
@State private var selectedBox = "Inbox"
let messageBoxes = ["Inbox", "Sent"]
var body: some View {
List(messages) { message in
NavigationLink(destination: {
Text(message.text)
}) {
VStack(alignment: .leading) {
Text(message.from).font(.headline)
Text(message.text)
}
}
}
.listStyle(.insetGrouped)
.navigationTitle(selectedBox)
.toolbar(content: {
Picker("Select", selection: $selectedBox) {
ForEach(messageBoxes, id: \.self, content: Text.init)
.pickerStyle(.segmented)
}
})
.onAppear {
print("onAppear")
}
.task(id: selectedBox) {
print("task start")
await loadMessages()
}
}
func loadMessages() async {
do {
let url = URL(string: "https://hws.dev/messages.json")!
let (data, _) = try await URLSession.shared.data(from: url)
messages = try JSONDecoder().decode([Message].self, from: data)
} catch {
messages = [
Message(id: 0, from: "Failed to load inbox.", text: "Please try again later.")
]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment