【问题标题】:SwiftUI: How to process BLE response and display new valuesSwiftUI:如何处理 BLE 响应并显示新值
【发布时间】:2020-05-25 12:27:54
【问题描述】:

我有一个与小型 BLE 设备通信的 swift 应用程序。我可以从设备发送请求并获得答案,但我很难更新我的 swiftui 视图中显示的值。

这是我尝试过的:

  1. 带有回调:

在实现所有 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() 在控制台中打印得很好,但组件没有更新。然后我读到只有视图的内部方法可以更新状态变量。

  1. 使用组合: 我更新了外围设备(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


    【解决方案1】:

    改为在正文中附加发布者的观察者,如下面的伪代码所示

    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"
                  ///...
                 }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 2023-02-06
      • 2017-04-24
      • 2020-09-08
      • 2012-01-08
      • 1970-01-01
      • 2017-08-23
      相关资源
      最近更新 更多