简体   繁体   中英

Polling for Response from BLE Adapter in Swift

Using a Wi-Fi socket based adapter, I can successfully poll for a response like so:

    func writeMessageWithResponse(message: String) -> [String] {
        self.waitingForResponse = true
        let runLoop = NSRunLoop.currentRunLoop()
        if self.response != nil {
            self.response?.removeAll()
        }

        writeMessage(message) // this will set self.waitingForResponse to false when a response is received

        while self.waitingForResponse && runLoop.runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture()) {
             // waiting for flag (self.waitingForResponse) to be set
        }

        return self.response!
    }

When I use this same code with a CBCentralManager BLE connection, the main thread is blocked and does not receive the response from the connection. I've tried changing the CBCentralManager to a different queue, but I get the same results.

Does anybody have an idea how to wait in a loop and still be able to receive a BLE response? I know a response is being sent, but the thread is blocked and not reading it.

Using an async function with a completionHandler won't work for this use case because I need a reusable function that can issue a chain of commands that each depend on the result of the last response.

The CBCentralManager and CBPeripheral APIs are not really designed for this. You should be using the methods provided by CBPeripheralDelegate and CBCentralManagerDelegate protocols. Initialize your central manager with a dedicated queue so that you can listen for responses to your peripherals and act on that data as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM