我尝试使用连接到蓝牙编写应用程序并发送一些数据并获得响应,但在尝试设置时出错:setNotifyValue 我用
开始搜索self.centralManager?.scanForPeripherals(withServices: [serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
连接到外围设备后
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
self.discoveredPeripheral = peripheral
self.discoveredPeripheral!.delegate = self
self.centralManager?.stopScan()
self.centralManager?.connect(self.discoveredPeripheral!, options: nil)
}
连接后我发现服务
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.discoveredPeripheral!.discoverServices([serviceUUID])
}
发现charachteristic后
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let services = peripheral.services{
for service in services {
if service.uuid.isEqual(serviceUUID) {
self.discoveredPeripheral!.discoverCharacteristics(nil, for: service)
}
}
} else{
print("errors")
}
}
我保存特征后尝试将setNotifyValue设为true
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let charachteristics = service.characteristics {
for charactiristic in charachteristics {
if charactiristic.uuid.isEqual(readCharacteristicUUID) {
self.readCharacteristic = charactiristic
} else if charactiristic.uuid.isEqual(writeCharacteristicUUID) {
self.writeCharacteristic = charactiristic
peripheral.setNotifyValue(true, for: charactiristic)
}
}
}
}
但是我得到了错误:
public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
print("didUpdateNotification")
if error != nil {
print((error!.localizedDescription))
}
}
在Android中不支持请求。
可以连接响应
有没有想法,有什么问题以及如何解决这个问题?
我尝试重启手机:CBCentralManager setNotifyValue: not working 但它没有帮助