Skip to content

Instantly share code, notes, and snippets.

@seanbehan
Created June 7, 2018 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanbehan/9213fc369ebcdc843a98a239e4b01677 to your computer and use it in GitHub Desktop.
Save seanbehan/9213fc369ebcdc843a98a239e4b01677 to your computer and use it in GitHub Desktop.
Reachability.swift class for detecting if network connection is available
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment