Search code examples
iosiphonecbcentralmanagerios-bluetoothcbperipheralmanager

CBCentralManager not calling didDiscoverPeripheral method when iPhone is locked


I am working on an app that scans for a specific peripheral, ones peripheral is found it should send the small amount of data.

App works in the foreground and also in background. I have also add this code in the plist

UIBackgroundModes bluetooth-central When iPhone is locked and peripheral starts advertising, it doesn't call

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {

I have done some research but couldn't find an answer.

Any help is appreciated.

Thanks


Solution

  • Save the discovered CBPeripheral instance.

    var activePeripheral: CBPeripheral!
    

    Or adding it into an array. If you are discovering more than one peripherals.

    var knownPeripherals = [CBPeripheral]()
    

    This way you can reconnect to whichever CBPeripheral you need (if it is available, obviously).

    This delegate method is invoked when a peripheral is disconnected optional func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error error: NSError?). You can try using it in your benefit by trying to reconnect to your peripheral.

    And finally you should check the Apple reference for performing long-term actions in background.

    Hope it helps!