15

感觉好像我在这里遗漏了一些东西,但是我如何才能获得有关配对受密码保护的外围设备是失败还是成功的反馈?

当我连接受密码保护的外围设备时,会弹出密码 UIAlertView 并且外围设备连接(调用didConnectPeripheral)并立即断开连接(didDisconnectPeripheral)。

[bluetoothManager connectPeripheral:peripheral options:nil];

现在,无论我输入正确的密码、错误的密码还是简单地按取消:在所有情况下,我都没有收到来自 CoreBluetooth 委托方法的任何反馈。

问题是我如何才能获得有关此过程的反馈?

4

1 回答 1

12

在此处发布多年的问题后,面临同样的问题。令人惊讶的是,Apple 没有提供任何关于配对是否成功的回调。但是,可以使用以下步骤得出相同的结论:

  1. 声明和初始化:
var centralManager: CBCentralManager?
var myPeripheral: CBPeripheral?
var peripheralManager: CBPeripheralManager?

centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
peripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main )

  1. CBCentralManager处于.poweredOn状态时扫描设备:
func centralManagerDidUpdateState(_ central: CBCentralManager) {
   if central.state == .poweredOn {
       centralManager?.scanForPeripherals(withServices: [CBUUID.init(string: "SERVICE-ID")])
   }
}
  1. 识别并连接到感兴趣的设备:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    //Identify the device to be connected
    if peripheral.name?.hasSuffix("DEVICE-SERIAL-NUMBER") ?? false {
        myPeripheral = peripheral
        peripheral.delegate = self
        centralManager?.connect(myPeripheral!, options: nil)
    }
}
  1. 发现连接设备的服务,然后发现这些服务的特征
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.discoverServices([CBUUID.init(string: "SERVICE-ID-STRING")])
    }

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {       
    let services = peripheral.services!
    let charId = CBUUID.init(string: “CHARACTERISTIC-ID”)
    for service in services {
        peripheral.discoverCharacteristics([charId], for: service)
    }
}
  1. 对于具有.notify属性的这些特征之一,写入一些写入类型为的数据.withResponse
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    let value = 1234
    let data = withUnsafeBytes(of: value) { Data($0) }
    for characteristic in service.characteristics!
    {
        if characteristic.properties.contains(.notify) {
            peripheral.setNotifyValue(true, for: characteristic)
            peripheral.writeValue(data, for: characteristic, type: .withResponse)   
        }
    }
}
  1. 检查此写入的响应以确定配对是否成功:
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { }

如果由于输入无效密码或用户取消配对而导致配对失败,您将收到“身份验证不足”的错误提示</p>

否则,对特征的写入将成功,错误对象将为 nil。

于 2019-02-12T06:48:03.060 回答