Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created March 31, 2017 01:53
Show Gist options
  • Save jamesmartin/9847466aba513de9a77507b56e712296 to your computer and use it in GitHub Desktop.
Save jamesmartin/9847466aba513de9a77507b56e712296 to your computer and use it in GitHub Desktop.
Swift example of iterating over all known Bluetooth devices on macOS
import IOBluetooth
// See https://developer.apple.com/reference/iobluetooth/iobluetoothdevice
// for API details.
class BluetoothDevices {
func pairedDevices() {
print("Bluetooth devices:")
guard let devices = IOBluetoothDevice.pairedDevices() else {
print("No devices")
return
}
for item in devices {
if let device = item as? IOBluetoothDevice {
print("Name: \(device.name)")
print("Paired?: \(device.isPaired())")
print("Connected?: \(device.isConnected())")
}
}
}
}
var bt = BluetoothDevices()
bt.pairedDevices()
@Moonmonkey-Beep
Copy link

Any way to get this to detect Bluetooth LE devices too? it doesn't seem to detect them.

@jamesmartin
Copy link
Author

Sorry, I haven't tried to detect any BTLE devices. What kind of thing are you trying and failing to detect? 🤔

@Moonmonkey-Beep
Copy link

Hi James, it seems to detect my 'normal' Bluetooth devices perfectly. Any Bluetooth LE devices are not detected, for example my Apple mouse which is normal bluetooth is picked up, but my Microsoft Modern Wireless Mobile Mouse is not.
I believe IOBluetooth should be able to handle both normal and LE on the Mac, I wondered if there was an easy way to get this to work?

@jamesmartin
Copy link
Author

I believe IOBluetooth should be able to handle both normal and LE on the Mac, I wondered if there was an easy way to get this to work?

Good question. Unfortunately I haven't needed to detect any bluetooth devices using this code snippet lately. I expect, given it's been six years, that the state of the art has moved on. I suggest hitting the latest Apple developer reference docs. Good luck! 🤞

@jangelsb
Copy link

jangelsb commented Jun 27, 2023

I was having issues with IOBluetoothDevice.pairedDevices() always returning an empty array but I found out that it is because we need the Bluetooth entitlement:

	<key>com.apple.security.device.bluetooth</key>
	<true/>

Screenshot 2023-06-27 at 6 07 00 AM

This on macOS 13.4 (Ventura)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment