Created
May 31, 2016 08:38
-
-
Save InstaRobot/5c0b423d1e701447b30e641e5bd2738c to your computer and use it in GitHub Desktop.
Правильный и работающий способ проверки соединения к сети
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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