URLSession in Swift: The Essential Guide [with Examples]

When you need to download or upload data in Swift, the URLSession class is the solution you should reach for.

URLSession handles the most common Internet protocols and allows you to:

  • Group and optimize data transfers.
  • Handle authentication, cookies, and caching.
  • Pause, resume, or cancel a download.
  • Download data in the background when your app is suspended.

AsyncStream and AsyncSequence for Swift Concurrency

Asynchronous sequences are a core feature of Swift concurrency. They allow you to process asynchronous events easily using simple for loops.

However, conforming to the AsyncSequence protocol to create an asynchronous sequence is not straightforward.

That’s where AsyncStream comes to the rescue, allowing you to easily create asynchronous sequences and quickly adapt old APIs to Swift concurrency.

AsyncImage in SwiftUI: Loading Images from URLs [with Caching]

AsyncImage is a convenient SwiftUI view that loads remote images using a URL. It’s especially useful in apps that interact with REST APIs since images are usually referenced using URLs in JSON data.

While Apple’s documentation might lead you to believe that AsyncImage caches the downloaded images, that is not the case. If you need image caching, you must implement your own custom solution.

Parsing JSON in Swift: The Complete Guide [With Examples]

Parsing JSON data is fundamental to any iOS app that performs remote REST API calls.

Thanks to the Codable protocols introduced in Swift 4, Swift has a native and idiomatic way to parse JSON data.

Paired with the JSONDecoder class, the Decodable protocol allows straightforward JSON decoding in a few lines of code and more sophisticated techniques to handle all the possible data formats and edge cases.