Search code examples
iosbluetoothcore-bluetooth

CBPeripheralManagerAuthorizationStatusNotDetermined


I had open bluetooth, but I use CBPeripheralManagerAuthorizationStatus to check it ,

CBPeripheralManagerAuthorizationStatus status = [CBPeripheralManager authorizationStatus];
if (CBPeripheralManagerAuthorizationStatusAuthorized == status) {

}
else if (CBPeripheralManagerAuthorizationStatusNotDetermined == status) {
}

I found status is CBPeripheralManagerAuthorizationStatusNotDetermined, not CBPeripheralManagerAuthorizationStatusAuthorized, so I don't know why, I use Xcode is 7.3, and my device is 6sPlus, so, it is because device is 6s series, I use my companion device, sometime also couldn't get bluetooth message, my companion device is 6s, so, I want to get your help, thanks.


Solution

  • Because the default state for bluetooth in your app is not determined, which means it has not asked for permission yet.

    This was originally answered over three years ago, so the original answer is no longer of value. The following is an updated answer for iOS 13.


    First, per Apple, you must ensure that you set the privacy values via your info.plist file to allow Bluetooth usage.

    Your app will crash if its Info.plist doesn’t include usage description keys for the types of data it needs to access, or it crashes. To access Core Bluetooth APIs on apps linked on or after iOS 13, include the NSBluetoothAlwaysUsageDescription key. In iOS 12 and earlier, include NSBluetoothPeripheralUsageDescription to access Bluetooth peripheral data.

    To request permission, just create a CBCentralManager, and so long as you have set the above keys properly, you will have the permission prompt called.

    Then, you can respond to changes via the centralManagerDidUpdateState delegate function.

    The following code snippet is a MVP demonstrating this:

    import CoreBluetooth
    
    final class BluetoothViewController: UIViewController {
        let centralManager = CBCentralManager()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            centralManager.delegate = self
        }
    }
    
    extension BluetoothViewController: CBCentralManagerDelegate {
        func centralManagerDidUpdateState(_ central: CBCentralManager) {
            switch central.state {
            case .poweredOn:
                print("ready to use")
            case .unauthorized:
                print("unauth")
            default:
                print("There are other states you should handle")
            }
        }
    }