Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, Check if particular website reachable

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

like image 695
Meghan Avatar asked May 31 '17 05:05

Meghan


1 Answers

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()
}
like image 151
Willjay Avatar answered Oct 19 '22 13:10

Willjay