How to check if iPhone is in Airplane Mode with Swift

后端 未结 4 1908
刺人心
刺人心 2021-01-22 04:50

I\'d like to check whether flight mode is activated. If so, I need to show a warning message.

How can I check whether flight (airplane) mode is active using Swift?

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-22 05:06

    You cant check the airplane mode is active or not , while you can check the cellular signal strength,

    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? = nil
    
    for subview in foregroundViewSubviews {
    
        if subview.isKind(of: NSClassFromString("UIStatusBarSignalStrengthItemView")!) {
            dataNetworkItemView = subview
            break
        }
    }
    
     if dataNetworkItemView == nil
     {
        return 0
     }
    return dataNetworkItemView?.value(forKey: "signalStrengthBars") as! Int
    
    } 
    

    Using this method you can get the signal strength and determine the device is in airplane mode or not . In airplane mode it will return 0 while in network it will return strength.

    Hope this will help you

提交回复
热议问题