1

I have an app that broadcasts a CBPeripheral with a small amount of text. I use the bluetooth-peripheral background mode to allow it to broadcast in the background.

When I scan from another device, in the foreground it works fine. I detect the peripheral, connect, discover the services then read the data from the service.

In the background however, there is something not quite right. I scan for peripherals with my service, and it finds it fine. I connect which also goes fine. I then discoverServices with my service which also goes fine as the didDiscoverServices callback is called. However in this callback, the peripheral has no services! peripheral.services is empty. It wouldn't have got this far if it didn't have the service, so what gives? The error in this callback is also nil

Everything works fine when broadcasting the CBPeripheral on iOS 12

EDIT ----- Spoke too soon, it seems that now my iOS 12 device has started showing the same symptoms. After a short while the CBPeripheral doesn't work.

Darren
  • 10,182
  • 20
  • 95
  • 162

1 Answers1

0

The problem was fixed by adding the CBAdvertisementDataLocalNameKey key when calling startAdvertising on the CBPeripheralManager. It seems this key is required if you want your CBPeripheral to keep broadcasting in the background. Apple docs fail to mention this.

Darren
  • 10,182
  • 20
  • 95
  • 162
  • Hello @Darren, for me this exact same problem continues to persist, despite giving the _CBAdvertisementDataLocalNameKey_ Code for initializing the peripheral advertising service: `// create our characteristics let characteristic = CBMutableCharacteristic.init(type: CBUUID(string: "12484b62-8da6-40b7-a54a-94ddf8f957a4"), properties: CBCharacteristicProperties.read, value: "dummy data to broadcast".data(using: String.Encoding.utf8), permissions: CBAttributePermissions.readable)` – Andreas Papageorgiou Feb 22 '20 at 21:01
  • could you please contact me, or reply to my above comment. the discovery does not work as expected and I get the same error as you, despite using the CBAdvertisementDataLocalNameKey – Andreas Papageorgiou Feb 26 '20 at 13:49
  • My issue was solved by adding the `CBAdvertisementDataLocalNameKey` to the `CBPeripheralManager`. I suggest you start a new question. – Darren Feb 26 '20 at 14:13
  • Thank you for your reply. Does your code still work now? i.e. can you discover a service from a peripheral that is backgrounded, connect to it, and read its characteristic? I will start a new discussion and link this question, but if you are still interested on the topic, please reach me on my email.. – Andreas Papageorgiou Feb 26 '20 at 16:19
  • 1
    Yes my code works fine now. I can leave an iPhone in standby for days and still discover and connect to a peripheral in the backgrounded app. – Darren Feb 26 '20 at 16:21