Skip to content

Instantly share code, notes, and snippets.

@StanislavK
Created March 1, 2018 09:12
Show Gist options
  • Save StanislavK/483e3437fc6c3d6856f3e3b21721a17e to your computer and use it in GitHub Desktop.
Save StanislavK/483e3437fc6c3d6856f3e3b21721a17e to your computer and use it in GitHub Desktop.
// Simple check if connected to internet
func isConnected() -> Bool {
// we need SCNetworkReachability object
guard let reachability = SCNetworkReachabilityCreateWithName(nil, "https://inloop-contacts.appspot.com/_ah/api/contactendpoint/v1/contact") else { return false }
// and flags
var flags = SCNetworkReachabilityFlags()
// read the "flags" into flags (via SCNetworkReachabilityGetFlags)
SCNetworkReachabilityGetFlags(reachability, &flags)
if !isNetworkReachable(with: flags) {
// Device doesn't have internet connection
return false
}
if flags.contains(.isWWAN) {
// On mobile data plan
return true
}
// on Wifi
return true
}
private func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
return isReachable && (!needsConnection || canConnectWithoutUserInteraction)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment