I have been learning about swift for sometimes. I have made an test app that shows user Battery Level and Storage details of the phone. Now i am exploring other possibilities. Is there anyway i can show the Battery Level of AirPods that are connected to the corresponding Device? If anyone has any solution or Guideline, that will be much Appreciated.
Asked
Active
Viewed 446 times
1 Answers
0
How about importing CoreBluetooth
then create an instance of CBCentralManager
.
if central.state == .poweredOn
then start scanning for airpods with the specific UUID
centralManagerInstance.scanForPeripherals(withServices: [airPodsUUID], options: nil)
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
let batteryLevel = Int(manufacturerData[1])
print("AirPods battery level: \(batteryLevel)%")
}
}
Alternatively, if you don't want to hardcode the UUID. you can use the centralManager.scanForPeripherals(withServices: nil, options: nil)
method to scan for all bluetooth devices and look for the advertisment data which contains the AirPods manufacturer ID (0x004C):
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data,
manufacturerData.count >= 1,
manufacturerData[0] == 0x4C {
// This is an AirPods device
let batteryLevel = Int(manufacturerData[1])
print("AirPods battery level: \(batteryLevel)%")
}
}

van
- 550
- 4
- 15