Last active
November 28, 2015 04:25
-
-
Save fnakstad/9fc39aae92842d84df4e to your computer and use it in GitHub Desktop.
Check network availability in Swift
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
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