Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan any Bluetooth Devices on iOS

I just want to get a list of any Bluetooth Devices around me, but CoreBluetooth display only Bluetooth Low Energy (4.0.

I don't want to connect to a device, but just display its name.

Is there a solution to do this?

like image 854
Valentin Gautier Avatar asked Jan 04 '23 12:01

Valentin Gautier


1 Answers

What you want to do is scan for all the CBPeripheral in your area. CBPeripheral is the class that does the broadcasting of any CBService(s) that the peripheral may advertise.

To scan for these peripherals you will need an instance of CBCentralManager. CBCentralManager is the class that does the scanning of your peripherals.

To do this you must instantiate your CBCentralManager

centralManager = CBCentralManager(delegate: self, queue: .main)

A good idea is before you scan for peripherals to tell your CBCentralManager that you only want to discover unique peripherals only once.

let options: [String: Any] = [CBCentralManagerScanOptionAllowDuplicatesKey: 
                              NSNumber(value: false)]

And when you tell your CBCentralManager to scan, don't specify any services of the advertising CBPeripheral(s). Instead pass nil for this parameter to indicate you want to discover all peripherals.

centralManager?.scanForPeripherals(withServices: nil, options: options)

The above call will begin the actual scanning for the bluetooth devices in the area. You will receive the callback in the CBCentralManagerDelegate methods to the result of your scan.


To get the name of the bluetooth devices, simple look at the name of the CBPeripheral(s) that are discovered. You do this through the CBCentralManagerDelegate method didDiscover peripheral: CBPeripheral.

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    print("Discovered \(peripheral.name ?? "")")
}
like image 167
Brandon A Avatar answered Jan 17 '23 23:01

Brandon A