1
我正在使用SimplePing來獲取我的swift應用程序中的延遲,但我沒有得到任何結果。Swift SimplePing不工作
這是代碼採取的形式,這裏的例子中SO:
import Foundation
public typealias SimplePingClientCallback = (String?)->()
public class SimplePingClient: NSObject {
static let singletonPC = SimplePingClient()
private var resultCallback: SimplePingClientCallback?
private var pingClinet: SimplePing?
private var dateReference: NSDate?
public static func pingHostname(hostname: String, andResultCallback callback: SimplePingClientCallback?) {
singletonPC.pingHostname(hostname, andResultCallback: callback)
}
public func pingHostname(hostname: String, andResultCallback callback: SimplePingClientCallback?) {
resultCallback = callback
pingClinet = SimplePing(hostName: hostname)
pingClinet?.delegate = self
pingClinet?.start()
}
}
extension SimplePingClient: SimplePingDelegate {
public func simplePing(pinger: SimplePing, didStartWithAddress address: NSData) {
pinger.sendPingWithData(nil)
}
public func simplePing(pinger: SimplePing, didFailWithError error: NSError) {
resultCallback?(nil)
}
public func simplePing(pinger: SimplePing!, didSendPacket packet: NSData!) {
dateReference = NSDate()
}
public func simplePing(pinger: SimplePing!, didFailToSendPacket packet: NSData!, error: NSError!) {
pinger.stop()
resultCallback?(nil)
}
public func simplePing(pinger: SimplePing, didReceiveUnexpectedPacket packet: NSData) {
pinger.stop()
resultCallback?(nil)
}
public func simplePing(pinger: SimplePing!, didReceivePingResponsePacket packet: NSData!) {
pinger.stop()
guard let dateReference = dateReference else { return }
//timeIntervalSinceDate returns seconds, so we convert to milis
let latency = NSDate().timeIntervalSinceDate(dateReference) * 1000
resultCallback?(String(format: "%.f", latency))
}
}
,並調用SimplePing在我的viewController我這樣做:
let simplePingClient = SimplePingClient()
simplePingClient.pingHostname("www.apple.com") { latency in
print("Your latency is \(latency ?? "unknown")")
self.labelTempsReponse?.text = latency
}
當我把一個斷點在該行:
simplePingClient.pingHostname("www.apple.com") { latency in
結果全部爲零(在resultCallBack,所述pingClient和dateReference)。我做了一項研究來解決這個問題,我發現一個類似於我的question,但在客觀的c。
任何人都可以幫助我嗎?