从昨天开始,我一直在寻找一个更简单的解决方案,以便仅对网站进行ping操作并检查它在Swift中是否返回200。
但是我发现的只是目标C中的解决方案。
在Swift中,我找到了类似的答案
var bsonDoc = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("query");
但是当我从其他函数调用它时,
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")
我如何简单地在Swift 4中ping并检查它是否返回200?
答案 0 :(得分:7)
如果您要“ 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()
}
(如果不在操场上跑步,请忽略操场上的东西。)
答案 1 :(得分:2)
答案 2 :(得分:2)
如果您要开发MacOS,那么Anton的答案是正确的。如果您是为iOS开发的,尽管您要ping非安全URL,则需要禁用App Transport Security(ATS)
。为此,您需要在Info.plist的NSAllowsArbitraryLoads
字段下将true
设置为NSAppTransportSecurity
。
更多信息,请访问:https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html-NSAppTransportSecurity
答案 3 :(得分:-1)
有一个第三方库可以用来实现相同的目的。
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)")
}
})