My app connects with a low energy peripheral when the peripheral goes out of range, I get didDisconnect
method callback, I simply call connect on the peripheral and whenever it comes back into range it connects.
Even in the background, if the app is suspended the by the iOS but since I have a pending connection, it wakes the app up and connects.
However, if the user turns the Bluetooth off, all the peripherals go into disconnected state, hence no pending connection remains. If the app is suspended by the iOS, and the user turns it back on after suspension, none of my delegate methods are called, I have added my initialization and state restoration methods below.
I initialize my central manager on background queue but whenever I receive a callback, I get the main queue to execute tasks:
- (void)initialize {
if (!self.centralManager) {
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) options:@{ CBCentralManagerOptionRestoreIdentifierKey:@"CBCentralManagerIdentifierKey" }];
}
}
My central state callback method
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
dispatch_async(dispatch_get_main_queue(), ^{
[SFUtil writeLog:@"centralManagerDidUpdateState"];
if (central.state == CBManagerStatePoweredOff) {
[SFUtil writeLog:@"CBManagerStatePoweredOff"];
[[NSNotificationCenter defaultCenter] postNotificationName:CB_MANAGER_BLUETOOTH_POWERED_OFF object:nil];
}
else if (central.state == CBManagerStatePoweredOn) {
[SFUtil writeLog:@"CBManagerStatePoweredOn"];
[self restoreConnections]; // here I reconnect to already known devices, retrieved from calling central method of retrievePeripheralsWithIdentifiers
[[NSNotificationCenter defaultCenter] postNotificationName:CB_MANAGER_BLUETOOTH_POWERED_ON object:nil];
}
});
}
My central restoration method:
- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *, id> *)dict {
dispatch_async(dispatch_get_main_queue(), ^{
[DataManagerInstance startBackgroundTaskIfInBackground]; // Here, I start a background task.
[self initialize];
});
}
I need to reconnect to the peripheral in the background when user reopens the app, but since centralManagerDidUpdateState method is never call when user turns the bluetooth back on from control centre or from settings. I cannot send the connect call.
When I manually launch the app, peripheral is in connecting state but doesn't reconnect.