Search code examples
iosswiftcore-bluetooththermal-printercbperipheral

Identifying the type of CBPeripheral before connecting


I recently created an app that uses CoreBluetooth on iOS to connect to a thermal printer. Everything is going just fine except for one thing. I can see over 20 bluetooth devices but only one is a thermal printer. Is there a way for me to know if this peripheral is a thermal printer or not before connection so that i can display/hide it ? Thanks


Solution

  • You're thinking about this backwards. You don't fetch the list of services and then decide whether to connect. You decide what services you want and scan for those.

    When you call scanForPeripherals(withServices:options:), you should almost always pass a list of services you support. If you're passing nil, then you're almost certainly calling it incorrectly unless you're building a general-purpose BLE scanner.

    The same is true of discoverServices(_:). You very rarely pass nil there. You pass the list of services you know how to deal with. The .services property is available as a convenience when you know you've already fetched the services, but it's rarely that useful. If you call discoverServices(_:) when it's unnecessary, the system will send you cached data immediately.