I'm trying to make an asynchronous network call using the async / await in Swift 5.5 but for some reason, it does not work as expected in my Swift Package.
let (data, response) = await URLSession.shared.data(for: request)
The above line of code works in a swift playground (request here being a URLRequest) but it fails to work inside my Swift Package (using swift tools version 5.5)
The error at first is: Type of expression is ambiguous without more context
but I realized it had to do with the tuple assignment so I changed the statement to just:
let data = await URLSession.shared.data(for: request)
And it gives me the error: Value of type 'URLSession' has no member 'data'
Futhermore, Xcode's code completion does not list .data(for:) while working in the Swift Package as opposed to the playground. Check the screenshots below for a better understanding.
CodePudding user response:
I'm surprised you didn't see the error
expression is 'async' but is not marked with 'await'
The function call URLSession.shared.data(for: request)
, because it's async
, should return an asynchronous continuation instead of an (Data,URLResponse)
tuple.
You would have two ways of handling that. You could immediately await
the response as suggested in comments:
let (data, response) = await URLSession.shared.data(for: request)
or you could use async let
to capture the continuation and then you can await it later:
async let requestTask = URLSession.shared.data(for: request)
print("Doing some other stuff")
let (data, response) = try await requestTask
CodePudding user response:
I've done enough research and concluded that a Swift Package (which is universally built) requires macOS 12.0 SDK for Swift Concurrency, and the current Xcode 13 release does not have it. It is only on the betas, so I'd have to use the latest beta or wait until Apple announces an Xcode release that supports the macOS 12 SDK.