how to determine battery level of airpods in swift
Asked Answered
C

1

9

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.

Carrousel answered 27/9, 2020 at 8:56 Comment(0)
H
2

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)%")
    }
}
Haul answered 22/3, 2023 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.