Code Snippet: URLSession.data(for: request) for iOS14

Posted by:

  • Avatar of Konstantin

    Konstantin

While it’s possible to use async/await methods in Swift when targeting older versions of iOS, Foundation does not offer a back-port of newer async method signatures introduced in iOS 15 and iOS 16.

This is a code snippet to emulate the data(for:) method introduced in iOS 15:

extension URLSession {
    @available(iOS, deprecated: 15.0, message: "Use data(for:) instead https://developer.apple.com/documentation/foundation/urlsession/3919872-data")
    func data(from url: URL) async throws -> (Data, URLResponse) {
        try await withCheckedThrowingContinuation { continuation in
            let task = self.dataTask(with: url) { data, response, error in
                if let error = error {
                    return continuation.resume(throwing: error)
                }

                guard let data = data, let response = response else {
                    return continuation.resume(throwing: URLError(.badServerResponse))
                }

                continuation.resume(returning: (data, response))
            }

            task.resume()
        }
    }
}

And this is a version using `URLRequest`:

import Foundation

extension URLSession {
    @available(iOS, deprecated: 15.0, message: "Use data(for:) instead https://developer.apple.com/documentation/foundation/urlsession/3919872-data")
    func data(for request: URLRequest) async throws -> (Data, URLResponse) {
        try await withCheckedThrowingContinuation { continuation in
            let task = self.dataTask(with: request) { data, response, error in
                if let error = error {
                    return continuation.resume(throwing: error)
                }

                guard let data = data, let response = response else {
                    return continuation.resume(throwing: URLError(.badServerResponse))
                }

                continuation.resume(returning: (data, response))
            }

            task.resume()
        }
    }
}

Tags