Skip to content

Instantly share code, notes, and snippets.

@InstaRobot
Created May 31, 2016 08:38
Show Gist options
  • Save InstaRobot/5c0b423d1e701447b30e641e5bd2738c to your computer and use it in GitHub Desktop.
Save InstaRobot/5c0b423d1e701447b30e641e5bd2738c to your computer and use it in GitHub Desktop.
Правильный и работающий способ проверки соединения к сети
import SystemConfiguration
class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {return false}
var flags : SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {return false}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
} // isConnectedToNetwork
} // class Reachability
/*
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
} else {
print("Internet connection FAILED")
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment