感觉我在这里遗漏了一些东西,但是如何获得有关配对受密码保护的外围设备失败或成功的反馈?
当我连接受密码保护的外围设备时,会弹出密码UIAlertView并且外围设备连接(调用didConnectPeripheral)并立即断开连接(didDisconnectPeripheral)。
[bluetoothManager connectPeripheral:peripheral options:nil];
现在我是否输入了正确的密码,错误的密码或只是按下取消:在任何情况下我都没有收到来自CoreBluetooth委托方法的任何反馈。
问题是如何获得有关此流程的反馈?
答案 0 :(得分:0)
在这里发布问题多年后,遇到了同样的问题。令人惊讶的是,Apple没有提供有关配对是否成功的任何回调。但是,可以使用以下步骤得出相同的结论:
var centralManager: CBCentralManager?
var myPeripheral: CBPeripheral?
var peripheralManager: CBPeripheralManager?
centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
peripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main )
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager?.scanForPeripherals(withServices: [CBUUID.init(string: "SERVICE-ID")])
}
}
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)
}
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)
}
}
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)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
}
如果由于无效的密码输入或用户取消配对而导致配对失败,您将收到一条错误消息,提示“身份验证不足”
否则将成功写入特征并且错误对象将为零