Wywoływanie API za pomocą URLSession
Pobieraj dane za pomocą async/await
Wywoływanie API za pomocą URLSession to bezpłatna lekcja SwiftUI Academy na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej SwiftUI Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs SwiftUI Academy zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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. 🚀
Ucz się Swift dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 30
- Lekcje
- 120
Często zadawane pytania
Czy lekcja „Wywoływanie API za pomocą URLSession” jest bezpłatna?
Tak — pełny tekst „Wywoływanie API za pomocą URLSession” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu SwiftUI Academy, przejdź na CoddyKit PRO. Kurs SwiftUI Academy zawiera 4 lekcji w sumie.
Co nauczysz się w „Wywoływanie API za pomocą URLSession”?
Pobieraj dane za pomocą async/await Ćwiczysz SwiftUI Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć SwiftUI Academy?
Nie wymagamy żadnego doświadczenia. SwiftUI Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.
Ile czasu zajmuje lekcja „Wywoływanie API za pomocą URLSession”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji SwiftUI Academy?
Tak. Każda lekcja SwiftUI Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Dekodowanie JSON za pomocą Codable
- Wywoływanie API za pomocą URLSession
- Modyfikator .task
- Stany wczytywania i błędów