1

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
}
Mitch
  • 111
  • 10
  • Doing this on the client is the wrong way. You should use network load balancing on the server side to provide resilience – Paulw11 Mar 31 '22 at 11:32
  • Take a look at [SCNetworkReachability](https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d). And you should not use `NSMutableURLRequest`, `NSURL` and `NSURLConnection.sendSynchronousRequest` in Swift 5 at all. – vadian Mar 31 '22 at 11:33

0 Answers0