更新时间:2023-11-26 21:10:04
有两点要检查:URL 本身是否有效,以及服务器响应没有错误。
There's two things to check: if the URL itself is valid, and if the server responds without error.
在我的示例中,我使用的是HEAD请求,它避免了下载整个页面,并且几乎不占用带宽。
In my example I'm using a HEAD request, it avoids downloading the whole page and takes almost no bandwidth.
func verifyURL(urlPath: String, completion: (isValid: Bool)->()) {
if let url = NSURL(string: urlPath) {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "HEAD"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (_, response, error) in
if let httpResponse = response as? NSHTTPURLResponse where error == nil && httpResponse.statusCode == 200 {
completion(isValid: true)
} else {
completion(isValid: false)
}
}
task.resume()
} else {
completion(isValid: false)
}
}
用法:
verifyURL("http://google.com") { (isValid) in
print(isValid)
}
用于游乐场,不要忘记启用异步模式以便能够使用NSURLSession:
For use in a Playground, don't forget to enable the asynchronous mode in order to be able to use NSURLSession:
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true