I'm working on the app that will connect with a smart device via BLE and communicate with it.
The question is: In what queue is the best practice to handle bluetooth events?
I've read a lot of tutorials and in all of them I found this:
centralManager = CBCentralManager(delegate: self, queue: nil)
They choose to handle bluetooth events in main queue (queue: nil
), but I suppose that it's not good practice. Because it could be a lot of queries send to peripheral device from central and a lot of answers send from peripheral to central.
I assume this might be the reason of the app working slowly and might detrimentally affect the productivity, am I right?
Will this flood the UI update queue?
I am using dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) for the CBCentralManager for some time in my Bluetooth projects and it is working flawlessly.
^ Scratch that. I wouldn't recommend using the global queue. The reason is that the global queue is a concurrent one and you probably want a serial one. Create a new DispatchQueue(label: "CentralManager")
and pass it to the CBCentralManager
.
All the delegate methods will be delivered to the queue you specify. If you do some very light operations on these methods, I guess you could keep the main queue. But it is better to use a background queue.
You should definitely use a seperate queue for the CBCentralManager
and preferrably also use it for all the communication with the CBPeripheral
object - so your main queue is not getting blocked.
dispatch_async
the events to your queue should not be a problem - as long as read/write requests are not getting delayed.
From Bluetooth perspective, I don't think queue the events is a best practice; except you want to delay the sending messages.