Swift BLE 外设 writeValue 不起作用

Posted

技术标签:

【中文标题】Swift BLE 外设 writeValue 不起作用【英文标题】:Swift BLE peripheral writeValue is not working 【发布时间】:2015-03-07 01:55:31 【问题描述】:

我当前的代码是:

@IBAction func sendData(sender: UISwitch) 
    if advertisingSwitch.on 
        var parameter = NSInteger(45)
        let data = NSData(bytes: &parameter, length: 1)
        if let connectedPeripheral = discoveredPeripheral 
            println("========= In connected peripheral \(connectedPeripheral)")
            //println("========= Send data is \(currentSendData)")
            println("========= Characteristic is \(sendDataCharacteristic)")
            println("========= data length is \(data.bytes)")
            self.sendDataToCentral(connectedPeripheral, characteristic: sendDataCharacteristic!, data: data)
        
    


private func sendDataToCentral(peripheral: CBPeripheral, characteristic: CBCharacteristic, data: NSData) 
    println("data is \(data)")
    peripheral.writeValue(data, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse)
    println("writed characteristic \(characteristic)")

当我检查外围设备时,它已连接显示:

BPeripheral: 0x1700ee980, identifier = E2377588-84CB-87ED-570A-B51614287B3C, name = TAv22u-FDF1, state = connected

特征是从已知 UUID 的服务扫描中获取。我确定我得到的特征具有“写”功能,即

<CBCharacteristic: 0x174086090, UUID = FFE9, properties = 0x8, value = (null), notifying = NO>

在我执行函数之后:

peripheral.writeValue(data, forCharacteristic: characteristic, type: CBCharacteristicWriteType.WithoutResponse)

特征中的值没有改变。我不知道我哪里错了。

【问题讨论】:

当您说值没有改变时,您如何验证这一点?从接收外围设备还是您只是在发送中心检查CBCharacteristic 的值? 您在peripheral:didWriteValueForCharacteristic:error:CBPeripheralDelegate 方法)中遇到什么错误? @Paulw11 我的意思是我的数据没有显示在接收外围设备中。我有一个可以更新屏幕数据的外围接收器。 @MichałCiuba 这个函数甚至没有被执行。 如果你写withoutResponseperipheral:didWriteValueForCharacteristic:error:不应该被调用。试试withResponsesendDataCharacteristic是怎么设置的? 【参考方案1】:
peripheral.writeValue(data, forCharacteristic: characteristic, type: 
 CBCharacteristicWriteType.WithResponse)

尝试.withResponse 并检查外围设备的响应。

【讨论】:

以上是关于Swift BLE 外设 writeValue 不起作用的主要内容,如果未能解决你的问题,请参考以下文章

未调用 BLE 外设委托

iOS ble 写入不改变值

Android BLE GATT 外设模式通知

适用于Android的蓝牙低功耗(BLE)外设应用程序

首次设置 BLE 外设名称的方式和时间

BLE在不同设备上的不同外设名称