我有一个与小型BLE设备通信的快速应用程序。我可以发送请求并从设备中获取答案,但是我无法更新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()在控制台中已很好地打印,但是组件未更新。然后,我读到只有视图的内部方法才能更新状态var。我更新了外设(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中访问尚未实例化的成员。
所以我不知道该怎么做。你们将如何处理?
最佳答案
改为在正文中附加发布者的观察者,如下面的伪代码中所示
struct ReaderInformations: View {
var ble: BleConnection
@State private var status: String = "status"
var body: some View {
VStack { // .. any your view
}
.onReceive(ble.passThroughSubjectPublisher) { response in // << here !!
switch response[0] {
self.status = "TEST"
///...
}
}
}
}