CBPeripheralManagerAuthorizationStatusNotDetermined

CBPeripheralManagerAuthorizationStatusNotDetermined

我打开了蓝牙,但我使用 CBPeripheralManagerAuthorizationStatus 来检查它,

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

}
else if (CBPeripheralManagerAuthorizationStatusNotDetermined == status) {
}

我发现状态是 CBPeripheralManagerAuthorizationStatusNotDetermined,不是CBPeripheralManagerAuthorizationStatusAuthorized,所以不知道为什么,我用的Xcode是7.3,而我的设备是6sPlus,所以,因为设备是6s系列,我用的是我的配套设备,有时候也上不了收到蓝牙消息,我的配套设备是6s,所以,我想得到你的帮助,谢谢。

因为您的应用中蓝牙的默认状态未确定,这意味着它尚未请求权限。

原来是三年多前的回答,原来的回答已经没有价值了。以下是 iOS 13 的更新答案。


首先,per Apple,您必须确保通过 info.plist 文件设置隐私值以允许使用蓝牙。

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.

申请权限,只需要创建一个CBCentralManager,只要你设置好以上键值,就会调用权限提示。

然后,您可以通过 centralManagerDidUpdateState 委托函数响应更改。

下面的代码片段是一个演示这一点的 MVP:

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