Skip to content

Instantly share code, notes, and snippets.

@backslash-f
Created November 26, 2019 13:49
Show Gist options
  • Select an option

  • Save backslash-f/dec6022bf34d23329856106467244432 to your computer and use it in GitHub Desktop.

Select an option

Save backslash-f/dec6022bf34d23329856106467244432 to your computer and use it in GitHub Desktop.
Check if the device is connected to a network
import SystemConfiguration
/// Returns `true` if the device is connected to a network, either WiFi or Cellular (4G, 5G, etc).
///
/// [source](https://stackoverflow.com/a/39782859/584548)
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)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Covers both Cellular and WiFi.
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment