Created
October 19, 2018 18:13
-
-
Save alansvits/5e97ba6f988f0f48d329e03915be0987 to your computer and use it in GitHub Desktop.
Check for internet connection with 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(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) | |
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 = SCNetworkReachabilityFlags(rawValue: 0) | |
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { | |
return false | |
} | |
/* Only Working for WIFI | |
let isReachable = flags == .reachable | |
let needsConnection = flags == .connectionRequired | |
return isReachable && !needsConnection | |
*/ | |
// Working for Cellular and WIFI | |
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 | |
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 | |
let ret = (isReachable && !needsConnection) | |
return ret | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source https://stackoverflow.com/questions/30743408/check-for-internet-connection-with-swift