Question

Our app currently uses CoreBluetooth to communicate with a smart watch. The issue is that if the app is (assumed) jetsammed (maybe after being backgrounded overnight), the only bluetooth event that seems to wake the app and initiate reconnections is powering off / powering on Bluetooth from iOS.

I do implement the following methods to ensure that reconnections happen, and that connections happen when the app retrieves connected peripherals (code has been stripped down to essential):

NSArray * connectedPeripherals = [_centralManager retrieveConnectedPeripheralsWithServices:@[kMyServiceUUID]];
for ( CBPeripheral * peripheral in connectedPeripherals )
{
    if ( peripheral.state == CBPeripheralStateConnected )
        continue;
    else
        [_centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:[NSNumber numberWithBool:TRUE]}];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [_centralManager connectPeripheral:peripheral options:@{CBConnectPeripheralOptionNotifyOnDisconnectionKey:[NSNumber numberWithBool:TRUE]}];
}

How can I ensure that my app is able to reconnect to watches if it has been in the background, say over night?

Along the same lines, how can I ensure that the app wakes up or is able to receive data from the watch if the app has in fact been jetsammed?

Was it helpful?

Solution

CBConnectPeripheralOptionNotifyOnDisconnectionKey tells Core Bluetooth that you are using the peripheral in event mode. That is, every event is handled by iOS and the user is presented a notification when something happens but your app is woken up only if the notification is swiped/tapped by the user. This is described in the documentation of this enum:

The value for this key is an NSNumber object. This key is useful for apps that have not specified the bluetooth-central background mode and cannot display their own alert. If more than one app has requested notification for a given peripheral, the one that was most recently in the foreground receives the alert. If the key is not specified, the default value is NO.

Instead you want connection mode. Specify the bluetooth-central backgrounding mode in you app's plist and implement your business logic accordingly. Additionally, you should consider implementing the restoration functions as well. All this is quite well documented in the questions here on SO and in the n Core Bluetooth Programming Guide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top