Simpliest solution to check if File exists on a webserver. (Swift)

倖福魔咒の 提交于 2019-11-27 22:37:39

Checking if a resource exists on a server requires sending a HTTP request and receiving the response. TCP communication can take some amount of time, e.g. if the server is busy, some router between the client and the server does not work correctly, the network is down etc.

That's why asynchronous requests are always preferred. Even if you think that the request should take only milliseconds, it might sometimes be seconds due to some network problems. And – as we all know – blocking the main thread for some seconds is a big no-no.

All that being said, here is a possible implementation for a fileExists() method. You should not use it on the main thread, you have been warned!

The HTTP request method is set to "HEAD", so that the server sends only the response header, but no data.

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
}
vito.royeca

Swift 3.0 version of Martin R's answer written asynchronously (the main thread isn't blocked):

func fileExistsAt(url : URL, completion: @escaping (Bool) -> Void) {
    let checkSession = Foundation.URLSession.shared
    var request = URLRequest(url: url)
    request.httpMethod = "HEAD"
    request.timeoutInterval = 1.0 // Adjust to your needs

    let task = checkSession.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if let httpResp: HTTPURLResponse = response as? HTTPURLResponse {
            completion(httpResp.statusCode == 200)
        }
    })

    task.resume()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!