Check internet access

1

How can I check in my app ( swift ) if the user has internet access?

    
asked by anonymous 21.10.2015 / 01:43

1 answer

2
Assuming you have a class for useful methods to access in a static way, it would be more or less like a 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.

    
21.10.2015 / 15:14