naptics / PlainPing

a very plain ping interface in swift
MIT License
58 stars 21 forks source link

Randomly fail to ping #32

Open fchen09 opened 1 year ago

fchen09 commented 1 year ago

Hi, I ping an existing IP, but sometimes it would pin fail. Any suggestions? I appreciate it! Here is my code, and I added a lock:

func ping(ip:String) {
    print(ip)

    let lock = NSLock()

    DispatchQueue.main.async {
    lock.lock()
        PlainPing.ping(ip, withTimeout: 1.0, completionBlock: { (timeElapsed:Double?, error:Error?) in
            if let latency = timeElapsed {
                let latencyStr = String(format:"%.2f",latency)
                print("latency (ms): \(latency)")

                    let alertController = UIAlertController(title: "PinoQuest", message: "Great! the IP is valid. (ms):     \(latencyStr)", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alertController.addAction(okAction)
                    UIApplication.shared.windows[0].rootViewController?.present(alertController, animated: true, completion: nil)
                } //過熱警告

            if let error = error {
                print("error: \(error.localizedDescription)")

                    let alertController = UIAlertController(title: "PinoQuest", message: "Error: \(error.localizedDescription)",    preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                    alertController.addAction(okAction)
                    UIApplication.shared.windows[0].rootViewController?.present(alertController, animated: true, completion: nil)
            }
        })
    lock.unlock()
    }

}
boenosimp commented 1 year ago

What is what is this for exactly?