0Pricing
SwiftUI Academy · Aula

Chamando APIs com URLSession

Busque dados usando async/await.

Chamando APIs com URLSession é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 2 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.

What URLSession Does

URLSession is Apple framework for talking to the network. You give it a URL and it fetches the response for you. 🌐

Building a URL

Start with a valid URL. The initializer is optional because text can be malformed, so unwrap it before using.

let url = URL(string: "https://api.example.com/users")!

The async Fetch Call

The modern way to fetch is async/await. You await data from a URL and your code reads top to bottom, like normal.

let (data, response) = try await
    URLSession.shared.data(from: url)

You Get Data and Response

The call returns two things: the raw data bytes and a response describing status. You usually decode the data next.

Combining Fetch and Decode

Fetch then decode in two short steps. await the bytes, then hand them to JSONDecoder to get a typed value.

let (data, _) = try await URLSession.shared.data(from: url)
let users = try JSONDecoder().decode([User].self, from: data)

Async Functions

Wrap network work in an async function. Marking it async lets you use await inside and keeps the UI responsive.

func loadUsers() async throws -> [User] { }

Why throws Matters

Networking can fail, so fetch functions are throws. Callers must try, which forces you to think about errors.

Checking the Status Code

Cast the response and read its statusCode. A value of 200 means success, while 404 or 500 signal problems.

let http = response as? HTTPURLResponse
if http?.statusCode == 200 { }

Reusing the Shared Session

For most apps, URLSession.shared is all you need. It is a ready-made session with sensible default settings.

Custom Requests

For headers or POST bodies, build a URLRequest. Set the method and fields, then pass the request to the session.

var request = URLRequest(url: url)
request.httpMethod = "GET"

Keep Networking Off the UI

Always do fetching in an async context, never on the main thread directly, so taps and scrolling stay smooth.

Quick Check

Quick check on fetching data from a URL.

Recap: URLSession

You can now await data from a URL with URLSession, check the status code, and decode the bytes inside an async throwing function. 🚀

Perguntas Frequentes

A aula “Chamando APIs com URLSession” é grátis?

Sim — o texto completo de “Chamando APIs com URLSession” é 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 “Chamando APIs com URLSession”?

Busque dados usando async/await. 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 2 de 4.

Quanto tempo leva a aula “Chamando APIs com URLSession”?

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