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()
@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