How can I check in my app ( swift
) if the user has internet access?
How can I check in my app ( swift
) if the user has internet access?
Functions.swift
class:
import SystemConfiguration
struct Functions {
static 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)
}
}
And then in your view classes, you would have something like this (with Swift , in this situation you do not need to import the class Functions
):
if Functions.isConnectedToNetwork() {
print("tem internet")
} else {
print("nao tem internet")
}
The return is a boolean
, so it says whether or not there is access to the internet, either by wifi or cellular network.