Simpliest solution to check if File exists on a webserver. (Swift)
对此有很多讨论,我了解使用委托方法并检查响应" 404 "的解决方案:
1 2 3 4 5 6 7 8 | var request : NSURLRequest = NSURLRequest(URL: url) var connection : NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)! connection.start() func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { //... } |
但是我想有一个简单的解决方案,例如:
1 | var exists:Bool=fileexists(sURL); |
因为与委托在同一类中会有很多请求,我只想使用函数fileexists()检查响应。
有任何提示吗?
更新
我想我必须像下面这样做一个同步请求,但是我总是得到0x0000000000000000作为响应::
1 2 3 4 5 6 7 8 9 | let urlPath: String = sURL; var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) var response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >=nil var error: NSErrorPointer = nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)! var err: NSError println(response) |
Martin R的答案的Swift 3.0版本异步编写(主线程未阻塞):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() } |
检查服务器上是否存在资源需要发送HTTP
请求并接收响应。 TCP通讯可能需要一些时间
时间量,例如如果服务器繁忙,则在
客户端和服务器无法正常工作
正确,网络已关闭等。
这就是为什么总是首选异步请求的原因。即使你以为
该请求应仅花费毫秒,有时可能是
某些网络问题导致的秒数。众所周知,
几秒钟的主线程是一个很大的禁忌。
话虽如此,这是一个可能的实现
您已被警告!
HTTP请求方法设置为" HEAD",以便服务器发送
仅响应标头,但没有数据。
1 2 3 4 5 6 7 8 9 10 11 | 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 } |