A way to calculate or get wifi strength on Swift o

2019-08-01 01:59发布

问题:

Looking for a way to either get or calculate the wifi strength of a device? Have seen examples of scraping the status bar but cannot get it to work on iOS 11:

func getSignalStrength() -> Int {
    let application = UIApplication.shared
    let statusBarView = application.value(forKey: "statusBar") as! UIView
    let foregroundView = statusBarView.value(forKey: "foregroundView") as! UIView
    let foregroundViewSubviews = foregroundView.subviews

    var dataNetworkItemView:UIView!

    for subview in foregroundViewSubviews {
        if subview.isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
            dataNetworkItemView = subview
            print("NONE")
            break
        } else {
            print("NONE")

            return 0 //NO SERVICE
        }
    }

    return dataNetworkItemView.value(forKey: "signalStrengthBars") as! Int
}

Any clever ideas?

Does not need to be approved by apple

回答1:

The code you have is for the mobile network(2G/3G/4G etc), not for WiFi network.

Try the code below in Swift4, it works on my iOS11:

private func wifiStrength() -> Int? {
    let app = UIApplication.shared
    var rssi: Int?
    guard let statusBar = app.value(forKey: "statusBar") as? UIView, let foregroundView = statusBar.value(forKey: "foregroundView") as? UIView else {
        return rssi
    }
    for view in foregroundView.subviews {
        if let statusBarDataNetworkItemView = NSClassFromString("UIStatusBarDataNetworkItemView"), view .isKind(of: statusBarDataNetworkItemView) {
            if let val = view.value(forKey: "wifiStrengthRaw") as? Int {
                //print("rssi: \(val)")

                rssi = val
                break
            }
        }
    }
    return rssi
}

How to get the WiFi strength on iPhoneX, check my answer in another post: Using Private API To read WiFi RSSI Value