9

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

Meghan
  • 1,004
  • 1
  • 15
  • 34
  • Check out this answer https://stackoverflow.com/a/9617166/3066450 – ebby94 May 31 '17 at 05:46
  • 2
    What's your definition of "reachable"? Even blocked sites tend to return some sort of page telling you the page has been blocked. So any basic check will make it seem like the page is "reachable". – rmaddy May 31 '17 at 06:05
  • @rmaddy : Its showing timeout. – Meghan May 31 '17 at 06:19
  • 1
    Your question is not clear (what are the criteria for a website not being reachable?) but I suppose you could make a HEAD request (to avoid downloading the whole page if it's reachable) and inspect the server response: https://stackoverflow.com/a/37134377/2227743 – Eric Aya May 31 '17 at 09:18

3 Answers3

5

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()
}
Willjay
  • 6,381
  • 4
  • 33
  • 58
  • This downloads the entire page instead of just checking for availability. – Eric Aya May 31 '17 at 06:06
  • 2
    How does this check if a page if blocked or not? The 1 second timeout will make it seem like most pages are not reachable if the page happens to take more than one second to download or the user's access is a little slow. – rmaddy May 31 '17 at 06:07
1
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)
}
Devin Pitcher
  • 2,562
  • 1
  • 18
  • 11
-3

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")
Dima
  • 23,484
  • 6
  • 56
  • 83