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

5

6

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?

Franciscofranciska answered 20/6, 2016 at 9:47 Comment(2)
This works for me: linkDeservedly
This is working. while i connected via wifi. but its not working while i connected via mobile data @DeservedlyFranciscofranciska
P
4

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.

Proportionate answered 20/6, 2016 at 10:0 Comment(4)
should i use same Reachability() class?Franciscofranciska
Yes. Do you have that library?Proportionate
No i am using it by making public classFranciscofranciska
Ok but you can also download that library online like from this : github.com/tonymillion/ReachabilityProportionate
M
3

Don't require 'Reachability' pod

Swift 4+ and Xcode 11+

    import SystemConfiguration    

    protocol Utilities {}
    extension NSObject: Utilities {
        enum ReachabilityStatus {
            case notReachable
            case reachableViaWWAN
            case reachableViaWiFi
        }

    var currentReachabilityStatus: ReachabilityStatus {

        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return .notReachable
        }

        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return .notReachable
        }

        if flags.contains(.reachable) == false {
            // The target host is not reachable.
            return .notReachable
        }
        else if flags.contains(.isWWAN) == true {
            // WWAN connections are OK if the calling application is using the CFNetwork APIs.
            return .reachableViaWWAN
        }
        else if flags.contains(.connectionRequired) == false {
            // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
            return .reachableViaWiFi
        }
        else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
            // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
            return .reachableViaWiFi
        }
        else {
            return .notReachable
        }
    }
}

In any method use the below condition

if currentReachabilityStatus == .notReachable {
    // Network Unavailable
 } else {
    // Network Available
 }
Monroe answered 9/1, 2020 at 11:18 Comment(0)
A
2

If you have any super Class in your application then use below code

override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)


        NSNotificationCenter.defaultCenter().addObserver(self, selector: "ShowNetConnectivity", name: SHOW_NO_INTERNET_CONNECTION, object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "DisssmissConnectivity", name: DISMISS_INTERNET_CONNECTION, object: nil)


        let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
        SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
            print(flags.rawValue)

            if (flags.rawValue == NotReachable.rawValue && flags.rawValue != ReachableViaWiFi.rawValue && flags.rawValue != ReachableViaWWAN.rawValue)
            {
                if(isConnectionAvailable == true)
                {
                    let nc = NSNotificationCenter.defaultCenter()
                    nc.postNotificationName(SHOW_NO_INTERNET_CONNECTION, object: nil)
                }
            }else
            {
                if(isConnectionAvailable == false)
                {
                    let nc = NSNotificationCenter.defaultCenter()
                    nc.postNotificationName(DISMISS_INTERNET_CONNECTION, object: nil)
                }
            }

            }, &context)

        SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)
    }

    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: SHOW_NO_INTERNET_CONNECTION, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: DISMISS_INTERNET_CONNECTION, object: nil)
    }
Agnate answered 20/6, 2016 at 9:52 Comment(0)
D
2

Here's how I do it and it works for me. In my viewDidLoad:

do {
        reachability = try Reachability.reachabilityForInternetConnection()
    } catch {
        print("Unable to create Reachability")
        return
    }

    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(MainViewController.reachabilityChanged(_:)),
                                                     name: ReachabilityChangedNotification,
                                                     object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        print("This is not working.")
        return
    }

And the reachabilityChanged

func reachabilityChanged(note: NSNotification) {

    let reachability = note.object as! Reachability

    if reachability.isReachable() {
        if reachability.isReachableViaWiFi() {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    } else {
        showNoConnectionAlert()
        print("Not reachable")
    }
}

Using this Reachability

Deservedly answered 20/6, 2016 at 12:50 Comment(0)
S
1

I use this pod repo to achieve not only wifi or mobile data. you can do much more with it and you can use it in ObjC or Swift.

Best regards.

Sawfly answered 15/7, 2019 at 18:36 Comment(3)
Why using pods and bind your code to an external dependency if you can achieve the goal with built-in tools?)Tubb
@Tubb why re-write the wheel if someone else has already coded it for you?Confessor
@Confessor Why be dependent on somebody’s code (and its interface, its hidden bugs, its constrained logic) if it is easily dine natively?Tubb

© 2022 - 2024 — McMap. All rights reserved.