iOS问题检查蓝牙是否开启

时间:2018-04-13 11:24:09

标签: ios swift bluetooth core-bluetooth cbcentralmanager

我需要检查蓝牙是否开启。

我使用此代码:

func startDetectingBluetoothState() {
        if self.centralManager == nil {
            self.centralManager = CBCentralManager(delegate: self, queue: self.workingQueue, options: [CBCentralManagerOptionShowPowerAlertKey: false])
        }
    }

func centralManagerDidUpdateState(_ central: CBCentralManager) {
        let state = central.state
        DispatchQueue.main.async { [weak self] in
            // notify observers about state change
            self?.stateObservers.invokeDelegates { stateObserver in
                stateObserver.bluetoothStateChanged()
            }
        }
    }

我在iPhone X 11.3上启动了应用程序(设置中的蓝牙已启用),然后几乎无法通过centralManagerDidUpdateState(_ central: CBCentralManager)进入state == .poweredOff。所以价值是错误的。然后我在设置中关闭蓝牙,centralManagerDidUpdateState(_ central: CBCentralManager)功能未被调用(因为它检测到的先前状态是.poweredOff),然后我打开蓝牙并且centralManagerDidUpdateState(_ central: CBCentralManager)被调用.poweredOn值。然后它会正确检测每个状态变化。但是,如果我重新启动应用程序并且蓝牙处于打开状态,则无法再次检测到它。如果在启动期间蓝牙处于关闭状态,则一切正常。

我有另一台设备iPhone 6+ 11.2.5,其中一切都是魅力所在:)

3 个答案:

答案 0 :(得分:1)

您需要实现CBCentralManagerDelegate。以下是可能帮助您检查条件的示例代码 -

 var centralManager:CBCentralManager!

 in init() or viewDidLoad()
 {
     centralManager = CBCentralManager()
     centralManager.delegate = self
 }

func centralManagerDidUpdateState(_ central: CBCentralManager) {

  if central.state == .poweredOn {
     print("Bluetooth is connected")
  }
  else if central.state == .poweredOff{
     print("Bluetooth is not Connected.")
  }
}

答案 1 :(得分:0)

使用此代码为您工作

 var centralManager:CBCentralManager!

 override func viewDidLoad()
{
    super.viewDidLoad()

    // This will trigger centralManagerDidUpdateState
    centralManager = CBCentralManager(delegate: self, queue: nil)

}

 func centralManagerDidUpdateState(_ central: CBCentralManager)
{
    print("Central Manager did update state")

    if (central.state == .poweredOn)
    {

        self.centralManager?.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
    }
    else 
     {
        // Bluetooth is unavailable for some reason

        // Give feedback
        var message = String()
        switch central.state
        {
        case .unsupported:
            message = "Bluetooth is unsupported"
        case .unknown:
            message = "Bluetooth state is unkown"
        case .unauthorized:
            message = "Bluetooth is unauthorized"
        case .poweredOff:
            message = "Bluetooth is powered off"
        default:
            break
        }
        print(message)

        UIAlertView(
            title: "Bluetooth unavailable",
            message: message,
            delegate: nil,
            cancelButtonTitle: "OK")
            .show()
    }
}

答案 2 :(得分:0)

此代码在不显示iOS权限警报的情况下有效。 Swift 5版本

typealias Completion = ((Any?)->Void)
class BLEManager: NSObject {
    static let shared = BLEManager()
    var manager: CBCentralManager?
    var completion: Completion?

    func enabled() -> Bool {
        if #available(iOS 13.0, *) {
            return CBCentralManager(delegate: nil, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: false]).authorization == .allowedAlways
        }
        else {
            let manager = CBCentralManager(delegate: nil, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: false])
            return manager.state != .poweredOn
        }
    }
    
    func requestAccess(_ completion: @escaping Completion) {
        self.completion = completion
        manager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true])
    }
}

extension BLEManager: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        completion?(central.state)
    }
}