检查蓝牙状态 - Swift 4

时间:2017-11-15 06:18:46

标签: ios swift core-bluetooth

我在Xcode中遇到蓝牙问题。我找不到一个很好的解决方案,如何检查蓝牙是否打开。我想要那个。我在网上搜索了一些解决方案,但没有什么对我有用。有关如何检查蓝牙的任何想法?我导入了CoreBluetooth类,我编写了这行代码:

if CBPeripheralManager.authorizationStatus() == .denied { code }
if CBPeripheralManager.authorizationStatus() == .authorized  { code }

2 个答案:

答案 0 :(得分:23)

为此实施CBCentralManagerDelegate委托。

 var manager:CBCentralManager!

 viewDidLoad() {      // Or init()
     manager          = CBCentralManager()
     manager.delegate = self
 }

委托方法:

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
        break
    case .poweredOff:
        print("Bluetooth is Off.")
        break
    case .resetting:
        break
    case .unauthorized:
        break
    case .unsupported:
        break
    case .unknown:
        break
    default:
        break
    }
}

答案 1 :(得分:0)

您将需要使用CBCentralManager并提供委托方法“centralManagerDidUpdateState”https://developer.apple.com/documentation/corebluetooth/cbcentralmanager

func centralManagerDidUpdateState(_ central: CBCentralManager)
{
    if central.state == .poweredOn
    {
        print("Searching for BLE Devices")

        // Scan for peripherals if BLE is turned on
    }
    else
    {
        // Can have different conditions for all states if needed - print generic message for now, i.e. Bluetooth isn't On
        print("Bluetooth switched off or not initialized")
    }
}