Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

ios - Ping a Website or an IP Address (or Check if a Website is Online) using Swift 4?

I have been searching since yesterday for a simpler solution to just ping a website & check if it returns 200 in Swift.

But all I'm finding are solutions in Objective C.

In Swift, I found some answers like

func pingHost(_ fullURL: String) {
        let url = URL(string: fullURL)

        let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
            if let httpResponse = response as? HTTPURLResponse {
                print(httpResponse.statusCode)
            }
        }

        task.resume()
    }

But when I call it from some other function like

self.pingHost("https://www.google.com")

It gives weird errors like

2018-09-26 12:46:34.076938+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
2018-09-26 12:46:35.082274+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 2
2018-09-26 12:46:36.083497+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect()-> No of tries: 3
2018-09-26 12:46:37.083964+0530 Net Alert[1608:52682] dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:5 Err:-1 Errno:1 Operation not permitted
2018-09-26 12:46:37.084497+0530 Net Alert[1608:52682] [] nw_resolver_create_dns_service_locked [C1] DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2018-09-26 12:46:37.087264+0530 Net Alert[1608:52682] TIC TCP Conn Failed [1:0x600003706e80]: 10:-72000 Err(-65563)
2018-09-26 12:46:37.088841+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> HTTP load failed (error code: -1003 [10:-72000])
2018-09-26 12:46:37.088990+0530 Net Alert[1608:52673] Task <2B08658D-5DFA-48E9-A306-A47ED130DD1F>.<1> finished with error - code: -1003

How do I just simply ping in Swift 4 & check if it returns 200?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're going to "ping" a website you'll want to use a HEAD request instead of a GET request. To see if a website is up you don't need the whole website, just the headers. It will save time and bandwidth:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

if let url = URL(string: "https://apple.com") {
  var request = URLRequest(url: url)
  request.httpMethod = "HEAD"

  URLSession(configuration: .default)
    .dataTask(with: request) { (_, response, error) -> Void in
      guard error == nil else {
        print("Error:", error ?? "")
        return
      }

      guard (response as? HTTPURLResponse)?
        .statusCode == 200 else {
          print("down")
          return
      }

      print("up")
    }
    .resume()
}

(Omit the playground stuff if not running in a playground.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...