2

Using the following code to re-publish my Bluetooth service, I intermittently get a crash with the error message below.

self.stopAdvertising()
peripheralManager.removeAllServices()
if let service = self.cbService {
  NSThread.sleepForTimeInterval(0.1)
  peripheralManager.addService(service)
  self.startAdvertising()
}

2016-06-03 09:32:10.262 BottleSimulator[180:3587] * Assertion failure in -[CBPeripheralManager addService:], /SourceCache/CoreBluetooth/CoreBluetooth-256/CBPeripheralManager.m:307 2016-06-03 09:32:10.270 BottleSimulator[180:3587] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Services cannot be added more than once'

Why am I getting this? I would think that the call to removeAllServices() would protect against this. I even added a sleep for testing, but it didn't stop the intermittent crashes.

Is there a more reliable way to re-publish a service?

davidgyoung
  • 63,876
  • 14
  • 121
  • 204
  • Why don't you start advertising at the end of the for loop? – Larme Jun 03 '16 at 13:43
  • Sure, I can try moving startAdvertising() to the end of the block -- but it is not a loop, it is just an if block protecting against a nil service. So I think it is equivalent either way. – davidgyoung Jun 03 '16 at 13:55
  • 1
    Why are you republishing the service like that anyway? I suspect you have a timing problem. You have unpublished the service but the Bluetooth process may not have had time to clean up before you add it again. If you do want to re-publish the service it would be better to create a new CBMutableService rather than reusing the existing one. – Paulw11 Jun 03 '16 at 14:06
  • The only point in restarting the service in the code shown is to force close any connections from centrals and start from a clean slate. I am doing this because I am building a peripheral simulator app that can pretend to be one of several peripherals. Each time I change which peripheral it is acting as, I need to start from a clean slate. Is there a better way? – davidgyoung Jun 03 '16 at 14:41

0 Answers0