How to check if server is responding in Swift 5

206 Views Asked by At

I'm looking for a Swift 5 version of something like the fileExists function (below). For context I have an app that is heavily dependent on interaction with a remote server. For resilience we have created a second remote server and want the app to check if the first one is available, and if not, use the second one. I have found possible solutions using URLSession.shared.dataTask but they all just display a message rather than return an alternative url to use. Any suggestions would be most welcome.

func fileExists(url : NSURL!) -> Bool {

    let req = NSMutableURLRequest(URL: url)
    req.HTTPMethod = "HEAD"
    req.timeoutInterval = 1.0 // Adjust to your needs

    var response : NSURLResponse?
    NSURLConnection.sendSynchronousRequest(req, returningResponse: &response, error: nil)

    return ((response as? NSHTTPURLResponse)?.statusCode ?? -1) == 200
}
0

There are 0 best solutions below