Written by Sean Behan on Fri Jun 08th 2018

Is your app connected to the internet? You can use this standalone class to check! There are no dependencies so you can copy/paste it into your project without needing to install another framework.

With this class it's as simple as running Reachability.isConnectedToNetwork()

import Cocoa
import SystemConfiguration
// Usage
// if Reachability.isConnectedToNetwork() {
//   print("We're online!")
// }
public class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }
        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability as! SCNetworkReachability, &flags) == false {
            return false
        }
        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired
        return isReachable && !needsConnection
    }
}

And here is a link to a gist Reachability.swift


Tagged with..
#ios #swift #macos #cocoa #networking #reachability #isconnectedtonetwork #online #xcode #apple

Just finishing up brewing up some fresh ground comments...