Check Internet access

Asked

Viewed 411 times

1

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

  • That code works perfectly here.

  • @Paulorodrigues I create a class and call a method or I can put in a class I already have (remembering that the one I have inherits viewController) ?

  • The good thing is you create this class and then call this method being static, like Reachability. isConnectedToNetwork (). So you can use it anywhere, not just in this your Viewcontroller.

  • @Paulorodrigues sorry my ignorance how could I do this p import? because I created it in a Swift file and it did not allow me to import it (like import) ? and this code returns me true or false to the internet ?

  • In Reachability (https://github.com/ashleymills/Reachability.swift) you can monitor the internet if it falls... and also know if it is connected to Wifi or 3G :)

1 answer

2

Assuming you have a class for useful methods for static access, it would be more or less like a class Functions.swift:

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 visualization 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, then it says whether or not there is access to the internet, be it by wifi or cellular network.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.