The answer by @sschale is nice, but NSURLConnection is deprecated, it's better to use NSURLSession now.
Here's my version of an URL testing class:
class URLTester {
class func verifyURL(urlPath: String, completion: (isOK: 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 {
completion(isOK: httpResponse.statusCode == 200)
} else {
completion(isOK: false)
}
}
task.resume()
} else {
completion(isOK: false)
}
}
}
And you use it by calling the class method with a trailing closure:
URLTester.verifyURL("http://google.com") { (isOK) in
if isOK {
print("This URL is ok")
} else {
print("This URL is NOT ok")
}
}
Swift 3.0 with URLSession
class URLTester {
class func verifyURL(urlPath: String, completion: @escaping (_ isOK: Bool)->()) {
if let url = URL(string: urlPath) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse, error == nil {
completion(httpResponse.statusCode == 200)
} else {
completion(false)
}
})
task.resume()
} else {
completion(false)
}
}
}
This is better than your answer because it only downloads the response headers instead of the whole page (also, it's better because asynchronous).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…