NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: How do I know that URLSession.shared.data throws an Error in SwiftUI

Forums > Swift

Below code catches an Error object "error" when the server is not available:

    do{
        let (data, urlResponse) = try await URLSession.shared.data(for: request)
    } catch {
        print(error)
    }

When I read up on the documentation of URLSession.shared.data it is nowhere mentioned that it also throws an error (for URLSession.shared.dataTask for example it states explicitly that an error item is part of the returned values).

I mean the code is working but how would I KNOW that it returns an error object? That part is absolutely not transparent to me.

   

The method signature for URLSession.data(for:delegate:) looks like this:

func data(
    for request: URLRequest,
    delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse
)

See that throws in there? That's what tells you the method throws errors.

   

Thank you sir, makes sense! :)

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.