Reputation: 1014
How to check reachability of particular website?
I am connected to wifi network for internet access, which have blocked some sites. How to check if I have access to those sites or not?
I have checked with Reachability class, but I can not check for particular website.
Currently I am using Reachability.swift
Upvotes: 9
Views: 5339
Reputation: 2762
func pageExists(at url: URL) async -> Bool {
var headRequest = URLRequest(url: url)
headRequest.httpMethod = "HEAD"
headRequest.timeoutInterval = 3
let headRequestResult = try? await URLSession.shared.data(for: headRequest)
guard let httpURLResponse = headRequestResult?.1 as? HTTPURLResponse
else { return false }
return (200...299).contains(httpURLResponse.statusCode)
}
Upvotes: 3
Reputation: 6459
I don't know what is the best practice, but I use HTTP request
to do so.
func checkWebsite(completion: @escaping (Bool) -> Void ) {
guard let url = URL(string: "yourURL.com") else { return }
var request = URLRequest(url: url)
request.timeoutInterval = 1.0
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("\(error.localizedDescription)")
completion(false)
}
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
// do your logic here
// if statusCode == 200 ...
completion(true)
}
}
task.resume()
}
Upvotes: 5
Reputation: 23624
The initializer you want to use is listed on that page.
You pass the hostname as a parameter:
init?(hostname: String)
// example
Reachability(hostname: "www.mydomain.com")
Upvotes: -3