After I have read the answer for this question I have found that using reachabilityWithHostName
does not work with a URL such as this one: mySite.com/serv
A possible solution for Swift is:
func verifyURL(urlPath: String, completion: @escaping (_ isValid: Bool) ->()) {
if let url = URL(string: urlPath) {
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { _, response, error in
if let httpResponse = response {
if httpResponse.getStatusCode() == 200 {
completion(true)
}
} else {
completion(false)
}
}
task.resume()
} else {
completion(false)
}
}
Then call the method like that:
verifyURL(urlPath: "www.google.com", completion: { (isValid) in
if isValid {
runYourCode()
} else {
print("URL: www.google.com is not reachable")
}
})