Use async URLSession with server-side Swift
Swift 5.5 introduced async/await features that are great for iOS apps, but outright revolutionary in the world of server-side Swift. Before the arrival of async, frameworks like Vapor had to rely on SwiftNIO’s event loops, which awesome as they are, often caused your code to end up a convoluted mess of nested callback and confusing data mappings.
So I moved to async as soon as I could. And now, I thought, why not try the new async URLSession too:
let (data, response) = try await URLSession.shared.data(from: url)
Works great! That is, until you then push it to your server and try to compile it on Linux…you’ll get:
error: type of expression is ambiguous without more context
What is the problem?
What does this cryptic error message mean? Well, in short it means that Swift cannot find the async version of this function. Turns out that even though it is already supported on iOS, it is not yet supported on Linux (as of 5.5.2).
What’s the solution?
Thankfully Swift provides withCheckedContinuation
and withCheckedThrowingContinuation
— methods intended to assist the migration from non-async to async code. You can read more about this here.
Now we can write an extension for URLSessions’s data method that wraps our non-async code within one of these helper methods:
Now we can again use URLSession together with async:
let (data, response) = try await URLSession.shared.asyncData(from: url)