Skip to content

Instantly share code, notes, and snippets.

@fnakstad
Last active November 28, 2015 04:25
Show Gist options
  • Save fnakstad/9fc39aae92842d84df4e to your computer and use it in GitHub Desktop.
Save fnakstad/9fc39aae92842d84df4e to your computer and use it in GitHub Desktop.
Check network availability in Swift
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
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