Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Choose queue for Bluetooth Central manager

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?

like image 826
Gusev Slava Avatar asked Jul 15 '16 07:07

Gusev Slava


2 Answers

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.

like image 124
vbgd Avatar answered Nov 19 '22 15:11

vbgd


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.

like image 23
p2pkit Avatar answered Nov 19 '22 17:11

p2pkit