我已经创建了蓝牙代表,并且蓝牙正确连接。
在我的蓝牙对象中,我调用了所需的功能:
// 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")
}
}
}
检查调试器
writeCharacteristic
存储正确的特性,但是当我在ViewController中调用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
。 最佳答案
按照@Larme的评论,我意识到我正在创建BLE对象的第二个实例,因此实现单例模式将解决此问题。