【发布时间】:2018-06-19 08:57:02
【问题描述】:
我已经创建了一个蓝牙代理并且蓝牙连接正确。
在我的蓝牙对象中,我调用了所需的函数:
// 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。
【问题讨论】:
-
您确定您使用的是同一个蓝牙类实例吗?
-
@Paulw11 我确实在这个新的 ViewController 中再次调用了 BluetoothLE.init(),然后将其委托给“新 ViewControllers”的自我。我猜这会创建一个新实例,不是吗?...
-
确实如此。我建议为您的
BluetoothLE使用 Singleton。 -
你能检查是否包含像 writeCharacteristic.properties.contains(.write) 这样的写权限吗?
标签: ios iphone swift swift4 core-bluetooth