tezvyn:

URLSession: The Core of iOS Networking

AI-drafted, machine-checkedSource: developer.apple.combeginner
URLSession: The Core of iOS Networking

URLSession is the engine for all network requests in Apple apps. Use it to fetch API data, download images, or upload files. The biggest footgun is blocking the main UI thread, which freezes your app; always perform network tasks asynchronously.

WHY IT EXISTS: Apps need to talk to the internet. Apple created URLSession to provide a single, powerful framework for all networking, replacing older, more complex APIs and reducing the need for third-party libraries for common tasks like fetching data or downloading files.

THE MENTAL MODEL: Think of URLSession as your app's dedicated networking department. You give it a URLRequest (a memo describing what you want), and it handles the entire process: making the connection, sending the request, and returning with the data, an error, or a file on disk. It manages all the low-level complexity for you.

HOW IT WORKS: You typically use the shared singleton, URLSession.shared, for basic requests. You create a task, like a dataTask for fetching data or a downloadTask for files, by providing a URL. The key is that you must call resume() on the task to start it. The work is done asynchronously, and when it's finished, a completion handler you provided is called with the results. Modern Swift with async/await makes this even cleaner, letting you await the result of URLSession.shared.data(from: url).

WHEN TO USE IT: Use it for virtually any network communication in an iOS, macOS, watchOS, or tvOS app. It's the correct tool for fetching JSON from a REST API, downloading large assets for offline use, and uploading user-generated content to a server.

WHEN NOT TO USE IT: There's almost no reason to avoid it. While a third-party library might offer syntactic sugar, URLSession's native integration and modern Swift syntax make it powerful and easy to use. You might not interact with it directly if you use a higher-level SDK (like Firebase or a GraphQL client) that manages networking for you, but it's still running URLSession under the hood.

ONE CANONICAL EXAMPLE: To fetch user data from an API, you first create a URL object for the endpoint. Then, using async/await, you can write let (data, response) = try await URLSession.shared.data(from: url). You then check the response's status code and use JSONDecoder to parse the received data into your Swift User model. This is the modern, standard pattern.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.