How to check cellular signal with Swift

Sometimes you need send an SMS verification, or check if your user is in a cellular area. BUT it’s not too easy…

Well… can be easy….

Before iOS 9, Apple provides a SDK to access cellular signal, but it stops. After this, we, developers, need some workarounds.

The mindset here is check the number of bars in the screen, but it’s not only the mindset, it’s what we will do!

Our code will get the elements of statusBar, find the signal bar and get the count of bars.

Have two ways, before iOS 13 and after.

static func getSignal() -> Int {
        if #available(iOS 13.0, *) {
            if let statusBarManager = UIApplication.shared.keyWindow?.windowScene?.statusBarManager,
               let localStatusBar = statusBarManager.value(forKey: "createLocalStatusBar") as? NSObject,
               let statusBar = localStatusBar.value(forKey: "statusBar") as? NSObject,
               let _statusBar = statusBar.value(forKey: "_statusBar") as? UIView,
               let currentData = _statusBar.value(forKey: "currentData") as? NSObject,
               let celluar = currentData.value(forKey: "cellularEntry") as? NSObject,
               let signalStrength = celluar.value(forKey: "displayValue") as? Int {
                return signalStrength
            } else {
                return 0
            }
        } else {
            guard let statusBarView = UIApplication.shared.value(forKey: "statusBar") as? UIView,
                  let foregroundView = statusBarView.value(forKey: "foregroundView") as? UIView,
                  let classStatusBar = NSClassFromString("UIStatusBarSignalStrengthItemView") else { return 0 }
            
            for subview in foregroundView.subviews {
                if subview.isKind(of: classStatusBar) {
                    if let signalStrengthBars = subview.value(forKey: "signalStrengthBars") as? Int {
                        return signalStrengthBars
                    }
                    break
                }
            }
            return 0
        }
    }

Now, if your device have cellular signal, this method will return the count of signal, if is a simulator or an iPad, will return 0 because haven’t the signal bar.

Pay me a coffee:

paypal

+7