EDIT: Following @RobertVaessen comment I implemented the following, however I am still unable to discover the services of the connected peripheral.
-(void) centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict{
id tmpObj = [dict objectForKey:CBCentralManagerRestoredStatePeripheralsKey];
NSArray * keys = [dict allKeys];
NSString * message = @"";
for (int i=0; i<[keys count]; i++) {
NSString * stringTmp = keys[i];
message = [message stringByAppendingString:@";"];
message = [message stringByAppendingString:stringTmp];
}
// message contains "kCBRestoredScanServices and kCBRestoredPeripherals
if ([tmpObj isKindOfClass:[NSArray class]]) {
NSArray * peripheralsArray = (NSArray*)tmpObj;
for (int i=0; i<[peripheralsArray count]; i++) {
id objTmp = peripheralsArray[i];
if ([objTmp isKindOfClass:[CBPeripheral class]]) {
CBPeripheral * tmpPeripheral = (CBPeripheral*)objTmp;
tmpPeripheral.delegate = self;
[tmpPeripheral discoverServices: self.bleServices];
// It would reach this part of the code but not discover any services
}
}
}
}
Now the doubt is:
I had already discovered services when the app was in foreground and first connected to the peripheral, does this mean that once the app is woken app again the CBCentralManager will be unable to discover the services?
Theoretical context:
Bluetooth LE state preservation process is described here (see section "Adding Support for State Preservation and Restoration"):
What I am trying to do:
I am implementing an app that uses BLE State preservation to maintain the connection with a hardware accessory (whilst running in background).
The issue I got is that whenever iOS wakes up my app following a BLE state preservation event my CBCentralManager is unable to discover the services. Weirdly the hardware peripheral "sees" the connection but the iOS app is unable to access it.
In other words: The following methods in the class implementing the CBCentralManager delegate gets called correctly but does not do much (see comments in green below):
-(void) centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary<NSString *,id> *)dict{
NSArray * peripherals = [self.central retrieveConnectedPeripheralsWithServices:self.bleServices];
for (int i=0; i < peripherals.count; i++) {
CBPeripheral * peripheral = (CBPeripheral*) peripherals[i];
if (peripheral == nil) {
// Never happens
}
else{
// Always happens - also hardware thinks that the peripheral is connected
peripheral.delegate = self;
[peripheral discoverServices:self.bleServices];
// Does not discover any services ! <------------- ERROR!
}
}
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
// Only gets called when [peripheral discoverServices:self.bleServices] is called whilst app is running (either in background or foreground).
}
PS: I have asked this also in the Apple Developer forum but had no reply so far.
PPS: I also have activated Background mode in my info.plist file: