0

I haven't been able to find a solid answer to this question anywhere on the internet, and I feel like there has to be a simple answer. I'm trying to test wether I have a connection to specific ip addresses and certain ports with Swift on Mac OS.

I really just want to return true/false if I'm able to connect to a URL, or specific ports associated with it.

Any ideas?

Paul B
  • 1,517
  • 14
  • 20
  • This question is very similar to this [one](https://stackoverflow.com/q/10801527). There are plenty of good answers. Also make sure to check this [one](https://stackoverflow.com/q/8812459) as well. I would recommend the following article: [https://marcosantadev.com/network-reachability-swift/](https://marcosantadev.com/network-reachability-swift/) It is rather solid. – Paul B Feb 22 '19 at 20:12

1 Answers1

2

Have a look at the Network framework. It is super powerful and flexible and allows direct access to protocols like TLS, TCP, and UDP for your custom application protocols. It is Swift-ready and easy to use.

import Network

let connection = NWConnection(host: "www.google.com", port: .https, using: .tcp)
connection.stateUpdateHandler = { (newState) in
    switch(newState) {
    case .ready:
    print("Handle connection established")
    case .waiting(let error):
    print("Waiting for network", error.localizedDescription)
    case .failed(let error):
    print("Fatal connection error", error.localizedDescription)
    default:
    break
    }
}
connection.start(queue: .main) // Use some other queue if doing it for real.

The code above will work even in Playground (and fire the stateUpdateHandler at least once). In real app stateUpdateHandler will be called every time the state changes. BTW, URLSession, is built upon this framework.

Paul B
  • 1,517
  • 14
  • 20