0Pricing
SwiftUI Academy · Aula

O Modificador .task

Carregue dados quando uma visualização aparecer.

O Modificador .task é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Loading When a View Appears

Often you want to fetch data the moment a screen shows. The .task modifier runs async work exactly when the view appears. ⏱️

Attaching .task

Add .task to any view and give it an async closure. SwiftUI starts that work as the view comes on screen.

List(users) { user in Text(user.name) }
    .task { await load() }

It Calls Async Code

Inside .task you can freely use await. That makes it the natural home for your URLSession fetch on appearance.

.task {
    users = try? await loadUsers()
}

Why Not onAppear

The older onAppear cannot await async work directly. The .task modifier is built for concurrency, so prefer it for loading.

Automatic Cancellation

When the view disappears, SwiftUI cancels the task for you. That stops wasted work and avoids updating a gone view. ✨

Reacting to an id

Pass an id to .task and it reruns whenever that value changes. Perfect for reloading when a selection updates.

.task(id: selectedID) {
    await loadDetail(selectedID)
}

Updating State After Fetch

Store results in @State so assigning them refreshes the UI. The view redraws as soon as the data arrives.

@State private var users: [User] = []

Handling Errors Inside

Wrap risky calls in do/catch inside the task. You can then set an error message that the view shows the user.

do { users = try await loadUsers() }
catch { errorText = "Failed" }

Runs on the Main Actor

A .task closure starts on the main actor, so updating state and UI from it is safe without extra hopping.

One Task per Lifetime

By default .task runs once per appearance. For repeated refresh use pull-to-refresh or a changing id instead.

Keeping the Closure Small

Call a named function from .task rather than stuffing logic inline. It keeps the view tidy and easy to read.

.task { await viewModel.refresh() }

Quick Check

Quick check on triggering async loads.

Recap: .task

You learned that .task runs async work when a view appears, cancels on disappear, can rerun on an id, and is the go-to place to fetch. 👍

Perguntas Frequentes

A aula “O Modificador .task” é grátis?

Sim — o texto completo de “O Modificador .task” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.

O que vou aprender em “O Modificador .task”?

Carregue dados quando uma visualização aparecer. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar SwiftUI Academy?

Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “O Modificador .task”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de SwiftUI Academy?

Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Decodificando JSON com Codable
  2. Chamando APIs com URLSession
  3. O Modificador .task
  4. Estados de Carregamento e Erro
← Voltar para SwiftUI Academy