Pawel Klapuch
Pawel Klapuch

Reputation: 490

CBL2CAPChannel not responsive while app is backgrounded

I'm facing an issue where L2CAP (or NSStream) stops notifying events to the app after app went to background (after 2-10 seconds). App is probably being suspended (as expected).

My expectation is that when there's BLE activity, app should be awaken by the system. The app supports 'background modes - uses LE Accessory. Also supports state restoration)

Here are some common use-cases (app is 'central')

  1. app triggered 'connect'.. app gets suspended.. peripheral comes in range -> app awaken (works)
  2. app is connected .. app gets suspended.. peripheral updates notifying characteristic -> app awaken (works)
  3. app is connected.. app gets suspended.. peripheral writes over L2CAP -> app awaken (does not work)

1 and 2 are very reliable (even after rebooting).

The 3 - does not work at all. Sadly I cannot find any relevant documentation so i assume it should be the same (as with characteristics)

From Apple (regarding 'bluetooth-central'):

When your app declares this, the system wakes it up from a suspended state to allow it to handle Bluetooth-related events

The main difference seems to be that L2CAP is built on top of NSStream - but I don't know what difference that makes on system level. NSStream runs on RunLoop.main (default).

Further on, if app is suspended, and peripheral performs L2CAP writes... (nothing happens), BUT then if peripheral notifies characteristic, it wakes up the app and it receives L2CAP messages + it can continue to receive L2CAP data for some time (2-10s) then it stops again. This could be some workaround (to always notify via characteristic) but I wish this was documented...

Is L2CAP not considered 'BLE' activity and will not wake the app by design?

Further from docs,

In addition, the system wakes up your app when any of the CBCentralManagerDelegate or CBPeripheralDelegate delegate methods are invoked, allowing your app to handle important central role events, such as when a connection is established or torn down, when a peripheral sends updated characteristic values, and when a central manager’s state changes.

This obviously does not include 'NSStream' callbacks...

Upvotes: 1

Views: 238

Answers (2)

Antony  Wong
Antony Wong

Reputation: 592

My Test result:

iOS 16.6.1: The L2CAP channel does not work in the background.

iOS 17.2.1: The L2CAP channel works in the background.

Upvotes: 0

faku
faku

Reputation: 441

iOS 17 seems to fix BLE L2CAP CoC communication in the background.

Upvotes: 1

Related Questions