Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i check mobile data or wifi is on or off. ios swift

in my app i am checking that if mobile data is off its showing the popup like check your data connection. for that i write this code

 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(kCFAllocatorDefault, UnsafePointer($0))
        }

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

        let isReachable = flags == .Reachable
        let needsConnection = flags == .ConnectionRequired

        return isReachable && !needsConnection

    }
}

but by this code its only check that wifi is connected or not. but if i try with 3g mobile data its always showing me that your mobile data is not connected. so how can i solve this?

like image 243
Jack.Right Avatar asked Dec 19 '22 16:12

Jack.Right


1 Answers

Try like below code:

Create object of reachability class like,

    var internetReachability = Reachability()

Now write below code in viewDidLoad(),

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
    self.internetReachability = Reachability.reachabilityForInternetConnection()
    self.internetReachability.startNotifier()
    self.updateInterfaceWithReachability(self.internetReachability)

Now create function to check reachabilty of wifi as well as data pack,

func updateInterfaceWithReachability(reachability: Reachability)
{
    let netStatus : NetworkStatus = reachability.currentReachabilityStatus()
    switch (netStatus.rawValue)
    {
    case NotReachable.rawValue:
        print("offline")
        break
    case ReachableViaWWAN.rawValue:
        print("online")
        break
    case ReachableViaWiFi.rawValue:
        print("online")
        break
    default :
        print("offline")
        break
    }
}

// Rechability update status
func reachabilityChanged(sender : NSNotification!)
{
    let curReach : Reachability = sender.object as! Reachability
    self.updateInterfaceWithReachability(curReach)
}

Hope this will help you.

like image 122
Jigar Tarsariya Avatar answered Feb 16 '23 00:02

Jigar Tarsariya