Swift, Check if particular website reachable
Asked Answered
S

3

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

Solemn answered 31/5, 2017 at 5:28 Comment(4)
Check out this answer https://mcmap.net/q/1244957/-checking-reachability-against-a-specific-page-in-a-urlExtraordinary
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".Newcomb
@Newcomb : Its showing timeout.Solemn
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://mcmap.net/q/1318725/-swift-verifying-is-valid-url-in-os-x-playgroundSplitting
S
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()
}
Snafu answered 31/5, 2017 at 5:46 Comment(2)
This downloads the entire page instead of just checking for availability.Splitting
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.Newcomb
S
3
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)
}
Seleneselenious answered 15/9, 2022 at 19:57 Comment(0)
B
-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")
Bigner answered 31/5, 2017 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.