Created
March 24, 2017 11:22
-
-
Save eleev/7016faa60c2ced48af126f7afe1ced2b to your computer and use it in GitHub Desktop.
Class-level extension for UIApplication for checking internet connectivity. Swift 3
This file contains 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
extension UIApplication { | |
class func isInternetAvailable() -> Bool { | |
var zeroAddress = sockaddr_in() | |
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() | |
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { | |
return false | |
} | |
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