Swift: try await URLSession.shared.data(from: url) exits without throwing and without result if endpoint is down

79 Views Asked by At

I have a .NET core WebApi endpoint with a PING method that simply returns "PONG" when called. In a SwiftUI app (XCode 15 with iOS 17.2 target) I use this code for calling it:

func ping () async throws -> String {
        
        let call = "\(baseURL)/Ping"
        
        guard let url = URL(string: call) else {
            throw SmartReaderError.invalidURL
        }
        
        do {
            
            let (jsonData, _) = try await URLSession.shared.data(from: url)
            let responseString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
            
            if responseString == "PONG" {
                return responseString! as String
            }
            else {
                return "KO"
            }
        } catch {
            return "KO"
        }
    }

For testing purposes I just kept the endpoint down. The call to URLSession.shared.data... doesn't return a value nor throws an error. It just makes func ping () exiting and the let responseString... is never reached. Even setting a breakpoint didn't clarified...

I expected that, if the http endpoint is unreachable or doesn't respond at least an error was thrown.

1

There are 1 best solutions below

0
Marcello Bassiato On

The issue was solved reducing URLSession.defaultConfig.timeoutIntervalForRequest value for pinging purposes.