In my project I have code that I found on this website that checks if the user doesn't have any internet (no wifi or cellular). The code works when a person with no connection opens the tab, but when they open the tab first and then lose connection it fails to detect that. How can I make it so that the function is triggered after the tab is loaded and they lose connection afterwards? Below is the code:
import SystemConfiguration
func connectedToNetwork() -> 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)
// For Swift 3, replace the last two lines by
// let isReachable = flags.contains(.reachable)
// let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}