【发布时间】:2020-05-25 12:27:54
【问题描述】:
我有一个与小型 BLE 设备通信的 swift 应用程序。我可以从设备发送请求并获得答案,但我很难更新我的 swiftui 视图中显示的值。
这是我尝试过的:
- 带有回调:
在实现所有 BLE 的 BleConnection.swift 文件中,我声明了一个回调 var onResponse: (([UInt8]) -> Void)? = nil
当收到来自设备的响应时,通过回调将数据推送到视图:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
...
if self.onResponse != nil {
self.onResponse!(characteristic.value!.bytes)
}
}
}
}
在有 swiftui 视图的 ReaderInformations.swift 文件中,我实现了回调并尝试使用 @State var 更新组件显示值,但没有成功。回调中的 print() 在控制台中打印得很好,但组件没有更新。然后我读到只有视图的内部方法可以更新状态变量。
- 使用组合: 我更新了外围设备(didUpdateValueFor)并发送了 BLE 设备响应,如下所示:
let passThroughSubjectPublisher = PassthroughSubject<[UInt8], Never>()
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
...
passThroughSubjectPublisher.send(characteristic.value!.bytes)
}
}
在视图中:
struct ReaderInformations: View {
var ble: BleConnection
@State private var status: String = "status"
private var cancelSet: Set<AnyCancellable> = []
init(bleInstance: BleConnection) {
passThroughSubjectPublisher.sink(receiveValue: { response in. // Escaping closure captures mutating 'self' parameter
switch response[0] {
self.status = "TEST". // This error because of the self
...
}
}).store(in: &cancelSet)
}
我也不工作,因为我尝试在 init 中访问一个尚未实例化的成员。
所以我在这里不知道该怎么做。你们将如何处理这个问题?
【问题讨论】:
标签: ios swift swiftui bluetooth-lowenergy