如果我readValue,iOS BLE外围设备writeValue将不起作用

时间:2018-12-13 23:50:39

标签: ios swift bluetooth-lowenergy core-bluetooth

我在MacOS应用中有一个外围设备,在iOS上有一个中央设备。中央具有以下代码:

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for characteristic in service.characteristics! {
        print(characteristic.uuid)
        switch characteristic.uuid {
        case bleCharacteristics().read:
            print("Read it!")
            peripheral.setNotifyValue(true, for: characteristic)
            peripheral.readValue(for: characteristic)
            break
        case bleCharacteristics().write:
            print("Write to it!")
            peripheral.writeValue("Heyooo".data(using: .utf8)!, for: characteristic, type: .withResponse)
            break
        case bleCharacteristics().notify:
            print("Subscribe to it!")
            peripheral.setNotifyValue(true, for: characteristic)
            break
        default:
            print("Got to the characteristics default somehow")
        }
    }
}

readValue可以正常工作,但是writeValue根本不起作用(因为在外围设备管理器的didReceiveWriteRequests中永远不会调用)。如果我注释掉readValue,则writeValue可以正常工作。在文档中没有任何地方说readValue是一个阻塞的异步操作或类似的事情,所以我不知道发生了什么。

如果有人对我做错了什么有什么想法,我将很有责任。

1 个答案:

答案 0 :(得分:0)

有时候您必须发布问题以找出答案。在我的外围代码中,我有:

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
    let response = "Hey there".data(using: .utf8)
    request.value = response
    peripheral.updateValue(response!, for: characteristics![0] as! CBMutableCharacteristic, onSubscribedCentrals: [request.central])
}

由于updateValue方法正在“读取”值,但没有关闭读取请求。添加行:

peripheral.respond(to: request, withResult: .success)

是响应读取请求并使其正确执行以使writeValue正常工作的正确方法。正确的外围代码:

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
    let response = "Hey there".data(using: .utf8)
    request.value = response
    peripheral.respond(to: request, withResult: .success)
}