从昨天开始,我一直在寻找一种更简单的解决方案,只需ping一个网站&检查它在Swift中是否返回200。
但我找到的都是目标C中的解决方案。
在Swift中,我找到了一些答案,比如
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()
}
但是当我从其他函数调用它时,比如
self.pingHost("https://www.google.com")
它会产生奇怪的错误,比如
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
我如何简单地在Swift 4中ping并检查它是否返回200?
发布于 2018-09-26 20:57:45
如果你要"ping“一个网站,你需要使用HEAD请求而不是GET请求。要查看一个网站是否正常,您不需要整个网站,只需要标题。它将节省时间和带宽:
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()
}
(如果不是在操场上跑步,则忽略操场上的内容。)
发布于 2018-09-26 15:31:31
有一个第三方库可以用来实现同样的目的。
https://github.com/ankitthakur/SwiftPing
let pingInterval:TimeInterval = 3
let timeoutInterval:TimeInterval = 4
let configuration = PingConfiguration(pInterval:pingInterval,
withTimeout: timeoutInterval)
print(configuration)
SwiftPing.ping(host: "google.com", configuration: configuration,
queue: DispatchQueue.main) { (ping, error) in
print("\(ping)")
print("\(error)")
}
SwiftPing.pingOnce(host: "google.com", configuration:
configuration,
queue: DispatchQueue.global()) { (response: PingResponse) in
print("\(response.duration)")
print("\(response.ipAddress)")
print("\(response.error)")
}
class PingResponse : NSObject {
public var identifier: UInt32
public var ipAddress: String?
public var sequenceNumber: Int64
public var duration: TimeInterval
public var error: NSError?
}
https://github.com/naptics/PlainPing
PlainPing.ping("www.google.com", withTimeout: 1.0, completionBlock: {
(timeElapsed:Double?, error:Error?) in
if let latency = timeElapsed {
self.pingResultLabel.text = "latency (ms): \(latency)"
}
if let error = error {
print("error: \(error.localizedDescription)")
}
})
发布于 2018-09-26 17:09:35
如果你是在为MacOS开发,安东的答案是正确的。但是,如果您正在为iOS进行开发,如果您正在pinging一个不安全的URL,则需要禁用App Transport Security(ATS)
。为此,您需要在Info.plist中的NSAppTransportSecurity
字段下将NSAllowsArbitraryLoads
设置为true
。
有关更多信息,请访问:https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html - NSAppTransportSecurity
https://stackoverflow.com/questions/52512244
复制相似问题