How to check if the user is connected to the internet(wifi and mobile data)- Swift

Asked

Viewed 186 times

0

I am using the following code to check if the user is connected to the internet:

   if Reachability.isConnectedToNetwork() == true {
        } else {
            let alert = UIAlertView(title: "Sem ligação à Internet", message: "Para aceder necessita de uma ligação à internet", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }

When I am connected by wifi I have no problem and the code works well, when I am connected by mobile data (3G/4G), then then if is not working and I get the error that I am not connected to the internet. Does anyone know why this is happening?

1 answer

2


I have an example I found researching,that will help you,in this example it works with 3G and Wi-Fi.

import Foundation
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(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
        }

        var flags: SCNetworkReachabilityFlags = 0
        if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
            return false
        }

        let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

        return isReachable && !needsConnection
    }

  if Reachability.isConnectedToNetwork() == true { <-- Seu código
        } else {
            let alert = UIAlertView(title: "Sem ligação à Internet", message: "Para aceder necessita de uma ligação à internet", delegate: nil, cancelButtonTitle: "OK")
            alert.show()
        }

}

Download the Reachability class here in this link and add to your project.

I advise you to take a look at this link,that will help you understand better.

  • And I’ve already done that. Thank you very much :)

Browser other questions tagged

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