I am trying to make some wrapper functions to handle some asynchronous BLE CoreBluetooth calls synchronously using closures. I want my run function to be blocked and not exit until receiving the completionHandler
callback. However, if I call my run
function multiple times in a loop, it does not wait for the completionHandler
callback and calls run
again. So in the end the callback is only received for the last run.
How can I modify my code so that it will wait in the run
function until completionHandler()
is called in the registerDidUpdateCallback
function?
I have tried reading a bunch of articles about closures, but I am still confused and my brain is fried.
func run(characteristic: CBCharacteristic, completionHandler: @escaping
CommandCompletionHandler) {
registerDidUpdateCallback(completionHandler)
motePeripheral.basePeripheral?.readValue(for: characteristic)
}
func registerDidUpdateCallback(completionHandler: @escaping CommandCompletionHandler) {
motePeripheral.setDidUpdateCharacteristicCompleteCallback { (updatedCharacteristic) -> Void in
let decoded = updatedCharacteristic.getDecoded()
print("Done reading and decoding Read
characteristic: \(updatedCharacteristic) with
Value: \ . (decoded)")
completionHandler(true)
}
}