0Pricing
SwiftUI Academy · Урок

Вызов API с URLSession

Получайте данные с помощью async/await.

«Вызов API с URLSession» — бесплатный урок SwiftUI Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения SwiftUI Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс SwiftUI Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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. 🚀

Часто задаваемые вопросы

Урок «Вызов API с URLSession» бесплатный?

Да — полный текст урока «Вызов API с URLSession» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс SwiftUI Academy, подпишись на CoddyKit PRO. Курс SwiftUI Academy содержит 4 уроков всего.

Чему я научусь в уроке «Вызов API с URLSession»?

Получайте данные с помощью async/await. Ты практикуешь SwiftUI Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать SwiftUI Academy?

Предыдущий опыт не требуется. SwiftUI Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Вызов API с URLSession»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке SwiftUI Academy?

Да. Каждый урок SwiftUI Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Декодирование JSON с Codable
  2. Вызов API с URLSession
  3. Модификатор .task
  4. Состояния загрузки и ошибок
← Назад к SwiftUI Academy