Reputation: 81
I am making an ios app which scan the BLE device in Minimize mode and in Foreground (active) mode of the app in iphone. In Foreground mode it is working but scan is not working if the app enter in minimize mode.
I also add "Required background modes" Keys
- (void)viewDidLoad
{
[super viewDidLoad];
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
self.centralManager = centralManager;
}
// method called whenever the device state changes.
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
// Determine the state of the peripheral
if ([central state] == CBCentralManagerStatePoweredOff) {
NSLog(@"CoreBluetooth BLE hardware is powered off");
}
else if ([central state] == CBCentralManagerStatePoweredOn) {
NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
}
else if ([central state] == CBCentralManagerStateUnauthorized) {
NSLog(@"CoreBluetooth BLE state is unauthorized");
}
else if ([central state] == CBCentralManagerStateUnknown) {
NSLog(@"CoreBluetooth BLE state is unknown");
}
else if ([central state] == CBCentralManagerStateUnsupported) {
NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(@"AdvertisementData:%@",advertisementData);
}
Upvotes: 0
Views: 496
Reputation: 1559
For the app to continue scanning in the background you need in this method: scanForPeripheralsWithServices:options:
to specify the services you wish to scan for, or else it wont work. For foreground scanning its not mandatory.
Upvotes: 0
Reputation: 13549
First off, you should be waiting until you get the centralManagerDidUpdateState:
callback with response state of CBCentralManagerStatePoweredOn
before you ever call scanForPeripheralsWithServices:options:
. It's actually surprising you're currently able to even scan in the foreground.
But the other main things to note are that the CBCentralManagerScanOptionAllowDuplicatesKey
flag is ignored whenever the app is not in the foreground, and the scanning interval is throttled down to around 1/60th of what it would be in the foreground. Therefore, you need to ensure the central has not discovered the peripheral before, and allow for ample time in the background since it takes longer. As long as the user has given permission to your app to run in the background, everything else should be fine. Just ensure your testing procedure is valid and not attempting to see duplicate peripherals.
Upvotes: 1