我已经创建了蓝牙代表并正确连接了蓝牙。
在我的蓝牙对象中,我调用了所需的功能:
// 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>
答案 0 :(得分:0)
在@Larme的评论之后,我意识到我正在创建BLE对象的第二个实例,因此实现单例模式将解决此问题。