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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…