HI, i'm trying to perform the following operations with the Core Bluetooth Framework of iOS:
-
Connection to peripheral
-
Services Discovery
-
Characteristics Discovery
-
Start Notify on a particular characteristic
These operations have to be triggered in background, when a callback not related to Core Bluetooth (Core Location Framework) fires up.
I have correctly set the Bluetooth Background settings for the app and when the application is put in background through the central button, all is ok: core location callback fires up and the core bluetooth steps are executed correctly. The problem comes when the application is killed by swiping up with the task manager: in this case when the core location callback fires up the phone is able to connect to the peripheral (1) but it does not discover services.
I'm using iPhone 6 with iOS 10.3.1 and micro nrf51822.
Here is my code:
CBCentralManager initialization (viewDidLoad)
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{ CBCentralManagerOptionRestoreIdentifierKey:@"myCentralManagerIdentifier"}];
Core Location Callback:
(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{
NSLog(@"*** enter region");
NSString *savedUuid = [[NSUserDefaults standardUserDefaults] stringForKey:@"preferenceUuid"];
if (savedUuid!=NULL){
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:savedUuid];
NSArray *arrayUuid = [NSArray arrayWithObjects:uuid, nil];
_knownPeripheral = [[self.centralManager retrievePeripheralsWithIdentifiers:arrayUuid] objectAtIndex:0];
}
if (_knownPeripheral!=NULL){
[self.centralManager connectPeripheral:_knownPeripheral options:nil];
}
}
CoreBluetooth Callbacks:
(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { [self.knownPeripheral discoverServices:nil]; }
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
// Core Bluetooth creates an array of CBService objects —- one for each service that is discovered on the peripheral.
for (CBService *service in peripheral.services) {
if (([service.UUID isEqual:[CBUUID UUIDWithString:K_BT_SERVICE_BATTERY]])) {
[peripheral discoverCharacteristics:nil forService:service];
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:K_BT_CHARACTERISTIC_BATTERY]]) {
[self.sensorTag setNotifyValue:YES forCharacteristic:characteristic];
}
}
How can i perform correctly the steps from 1) to 4) when the application is awaked from a killed state?
Thank you in advance