Check Bluetooth status - Swift 4

Franz L picture Franz L · Nov 15, 2017 · Viewed 16.6k times · Source

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 }

Answer

Sharad Chauhan picture Sharad Chauhan · Nov 15, 2017

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
    }
}