How can I determine if the iPhone user's Bluetooth is turned off or on?

I am trying to detect that the iPhone user's bluetooth is on or off. If it is turned off, I want to send a notification to the user to turn it on. So far I have done this:

import CoreBluetooth class ViewController: UIViewController, CLLocationManagerDelegate,AVCaptureMetadataOutputObjectsDelegate,CBManager { var myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) { print(#function) if peripheral.state == CBManagerState.poweredOn { print("Broadcasting...") // myBTManager!.startAdvertising(_broadcastBeaconDict) } else if peripheral.state == CBManagerState.poweredOff { print("Stopped") myBTManager!.stopAdvertising() } else if peripheral.state == CBManagerState.unsupported { print("Unsupported") } else if peripheral.state == CBManagerState.unauthorized { print("This option is not allowed by your application") } } 

But as you see in the picture, something is wrong. enter image description here

Could you help me solve this problem, I am new to the fast CoreBluetooth technology. I also use Reachability to detect Wi-Fi connections, so if it also works for Bluetooth, I would rather use Reachability.

+5
source share
2 answers
  • You must implement the CBPeripheralManagerDelegate protocol, so replace CBManager in the class definition line with CBPeripheralManagerDelegate .

  • In Swift 3, the signature of peripheralManagerDidUpdateState now:

     func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) 
  • You cannot initialize CBPeripheralManager time when creating a class, since self is only available after the class is initialized. Instead, make your property:

     var myBTManager: CBPeripheralManager? 

    and initialize it in viewDidLoad :

     override func viewDidLoad() { ... myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil) ... } 
+4
source

You can use the CBCentralMangerDelegate method:

  public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { if central.state == .poweredOn { //Bluetooth is on } else if central.state == .poweredOff { //Bluetooth is off } } 
0
source

Source: https://habr.com/ru/post/1261454/


All Articles