Saturday, 4 August 2018

Can't connect to AirPods via BLE

I am trying to connect automatically to my AirPods with a simple app using BLE. I get the name of the device and the status to "connecting", but for some reason I can't connect to it. Function 'didConnect peripheral' is never triggered.

I tried all different approaches from tutorials and from other posts, tried to store the peripheral data in an array to keep the reference but nothing seem to work.

Is there any step which I can get some extra info between 'didDiscover' and 'didConnect'?

Working in XCode 9.2, using Swift 4 and iOS 11.2 on iPhone.

Here's my code:

let deviceName = "AirPods de Roger"
var isConnected = false

var manager: CBCentralManager!
var peripheralBLE: CBPeripheral?

override func viewDidLoad() {
    super.viewDidLoad()
    manager = CBCentralManager(delegate: self, queue: nil)
}

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch manager.state {
    case.poweredOff:
        print("BLE service is powered off")
    case.poweredOn:
        print("BLE service is powered on and scanning")
        manager.scanForPeripherals(withServices: nil, options: nil)
    default:
        print("BLE service in another state")
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    if peripheral.name == deviceName && isConnected == false {
        self.manager.stopScan()
        self.peripheralBLE = peripheral
        self.peripheralBLE?.delegate = self
        manager.connect(peripheral, options: nil)
        isConnected = true
        print("\(peripheral.name) pre-connected")
    }
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    lblConnected.isHidden = false
    print("AirPods Connected")
    peripheral.discoverServices(nil)
}



from Can't connect to AirPods via BLE

No comments:

Post a Comment