をチェックするには、2つのものがあります:URL 自体が有効であること、およびエラーのないサーバー応答した場合場合。
私の例では、HEADリクエストを使用していますが、ページ全体のダウンロードを避け、帯域幅はほとんどありません。
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を使用することができるようにするために、非同期モードを有効にすることを忘れないでください:
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true