Are there more sophisticated alternatives to Apples Reachability class?

1.7k views Asked by At

Apple has created that famous Reachability class but looking at the code I don't trust it much. The formatting and header is messy.

Also it provides no help for showing that "You have no internet!" alert.

I just want to do:

  • At some point download a XML.

  • When there is no internet, show alert.

  • When internet disconnects while downloading the XML, show alert.

In my app the user taps no download button it all happens automatically in the background.

That's it. Really. I spent now 3 hours with Reachability my brain just rejects it.

Did someone create a clever alternative with a clean header and clean code? Something that is really simple to use?

3

There are 3 answers

0
Proud Member On BEST ANSWER

I've found one on GitHub: https://github.com/tonymillion/Reachability

Note: First find != necessarily best find.

1
dispatchMain On

Maybe its too late to respond, but following answer can help someone looking for solution to same problem, as I answered here.

Easiest way to detect Internet connection on iOS?

0
Paul B On

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
// To try a connection to a host
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: .global(qos: .background))

// 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.

// To get general connection status:

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        print("Not connected")
    }
    else if path.usesInterfaceType(.cellular) {
        print("Cellular 3/4/5g connection")
    }
    else if path.usesInterfaceType(.wifi) {
        print("Wi-Fi connection")
        print(path.status)
    }
    else if path.usesInterfaceType(.wiredEthernet) {
        print("Ethernet connection")
    }
}

monitor.start(queue: .global(qos: .background))