Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Bluetooth status - Swift 4

I have a problem with the Bluetooth in Xcode. I can’t find a great solution on how to check if Bluetooth is on or not. I want just that. I searched around the web some solution, but nothing works for me. Any idea on how to check Bluetooth? I imported the CoreBluetooth class and I made this line of code:

if CBPeripheralManager.authorizationStatus() == .denied { code }
if CBPeripheralManager.authorizationStatus() == .authorized  { code }
like image 612
Francesco Laiti Avatar asked Nov 15 '17 06:11

Francesco Laiti


2 Answers

Implement CBCentralManagerDelegate delegate for that.

 var manager:CBCentralManager!

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

Delegate method :

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
    }
}
like image 178
Sharad Chauhan Avatar answered Nov 15 '22 23:11

Sharad Chauhan


you will need to use CBCentralManager and it provide delegate method "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")
    }
}
like image 2
Waseem Avatar answered Nov 15 '22 23:11

Waseem