CoreBluetooth配对反馈/回调

时间:2015-01-08 09:07:49

标签: ios core-bluetooth cbperipheral

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

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

[bluetoothManager connectPeripheral:peripheral options:nil];

现在我是否输入了正确的密码,错误的密码或只是按下取消:在任何情况下我都没有收到来自CoreBluetooth委托方法的任何反馈。

问题是如何获得有关此流程的反馈?

1 个答案:

答案 0 :(得分:0)

在这里发布问题多年后,遇到了同样的问题。令人惊讶的是,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?) {

 }

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

否则将成功写入特征并且错误对象将为零