CoreBluetooth特性值被覆盖为零

时间:2018-06-19 08:57:03

标签: ios iphone swift swift4 core-bluetooth

我已经创建了蓝牙代表并正确连接了蓝牙。

在我的蓝牙对象中,我调用了所需的功能:

// Characteristic being targeted
var writeCharacteristic: CBCharacteristic!

public func peripheral(_ peripheral: CBPeripheral, 
    didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    guard let characteristics = service.characteristics else {
        return
    }
    print(characteristics)
    for characteristic in characteristics {
        switch (characteristic.uuid) {
        case (serialUUID) :
            print("serialPortRXCharacterUUID: \(service.uuid)")
            writeCharacteristic = characteristic  
        default:
            print("nothing")
        }
    }
}

当我在ViewController中调用writeCharacteristic时,检查调试器writeToDevice会存储正确的特性。

// View Controllers function
@IBAction func writeToDevice(_ sender: UIButton) {
    bluetoothManager.writeToPeripheral(message: "Test", peripheral: peripheral)
}

在蓝牙类对象中调用writeToDevice函数,如下所示:

func writeToPeripheral(message: String, peripheral: CBPeripheral) {
    if let data = message.data(using: String.Encoding.utf8) {
        let datareturn = String(bytes: data, encoding: .utf8)
        print(writeCharacteristic)
        peripheral.writeValue(data, for: writeCharacteristic!, type: .withoutResponse)
    }
}

调试器后writeCharacteristic从设备连接时的值开始,但在我从另一个视图控制器调用该按钮后,writeCharacteristic似乎又回到nil。 / p>

1 个答案:

答案 0 :(得分:0)

在@Larme的评论之后,我意识到我正在创建BLE对象的第二个实例,因此实现单例模式将解决此问题。