checking reachability against a specific page in a URL

前端 未结 3 834
梦毁少年i
梦毁少年i 2020-12-15 11:59

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

3条回答
  •  -上瘾入骨i
    2020-12-15 12:27

    Swift 5

    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")
        }
    })
    

提交回复
热议问题