CoreBluetooth配对反馈/回调

问题描述 投票:6回答:1

这感觉就像我失去了一些东西,但我怎么能得到是否配对保护周边失败或成功通行码的反馈?

当我连接外围是密码保护密码UIAlertView中弹出,外围连接(didConnectPeripheral叫),并立即断开(didDisconnectPeripheral)。

[bluetoothManager connectPeripheral:peripheral options:nil];

现在,我是否输入了正确的密码,错密码或直接按取消:在所有场合,我没有收到来自CoreBluetooth委托方法的任何反馈。

现在的问题是我怎么能得到这个过程中的反馈?

ios core-bluetooth cbperipheral
1个回答
1
投票

经过多年的问题面临着同样的问题被张贴在这里。令人惊讶的苹果并没有提供关于配对是否成功的任何回调。然而,下面的步骤可以用来推断相同:

  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?) {

 }

如果配对是因为用户的无效的密码输入或取消不成功,你会得到一个错误说“认证是不够的”

否则写入性能将是成功的和错误的对象将是零

© www.soinside.com 2019 - 2024. All rights reserved.