본문 바로가기
Swift/swiftUI

[SwiftUI] TaskModifier

by 마라민초닭발로제 2024. 5. 6.

 

 

코드전문

//
//  TaskModifier.swift
//  TIL_TCA
//
//  Created by MaraMincho on 5/5/24.
//

import Foundation
import SwiftUI

struct Message: Decodable, Identifiable {
    let id: Int
    let from: String
    let text: String
}

struct TaskModifierView: View {
  @State private var messages = [Message]()
  
  var body: some View {
    NavigationView {
      List(messages) { message in
        VStack(alignment: .leading) {
          Text(message.from)
            .font(.headline)
          
          Text(message.text)
        }
      }
      .navigationTitle("Inbox")
      .onAppear{
        print("View is appeard")
      }
      .task {
        print("Task was Started")
        await loadMessages()
        print("Task was end")
      }
    }
  }
  
  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.")
      ]
    }
  }
}

#Preview {
  TaskModifierView()
}

 

 

TaskModifier

Adds an asynchronous task to perform before this view appears.

 

Use this modifier to perform an asynchronous task with a lifetime that matches that of the modified view. If the task doesn’t finish before SwiftUI removes the view or the view changes identity, SwiftUI cancels the task.

 

뷰의 lifetime에 맞춰서 비동기작업을 넣을 수 있습니다. 또한 view가사라지거나 변해도 이전 작업들을 자동으로 취소시킵니다. 실제 lifeTime에 대한 코드도 다음과 같이 동작합니다. 

 

 

 

 

 

 

참고자료 

https://www.hackingwithswift.com/quick-start/concurrency/how-to-run-tasks-using-swiftuis-task-modifier

https://developer.apple.com/documentation/swiftui/view/task(priority:_:)