When using scanForPeripheralsWithServices:options, I'm able to discover a service when using
// Scanning with nil services will return all devices.
NSLog(@"Looking for any service.");
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
however when specifying the service in advance using the service identifier obtained from the Bluetooth device via the code below, I'm unable to discover the device.
#define DEVICE_INFO_SERVICE_UUID @"180a"
NSArray *services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:DEVICE_INFO_SERVICE_UUID], nil];
[self.centralManager scanForPeripheralsWithServices:services options:nil];
What's wrong?
[-CBCentralManager scanForPeripheralsWithServices:options:] only returns peripherals that actively advertise that they support a certain service.
If the service you are looking for is not advertised by the peripheral, you need to connect to it, and then discover the service you wish to access.
As space in the advertisement packets (that are processed when scanning) is limited, typically only the major service is advertised. Device Information Service is typically available on most BLE peripherals, and, therefore, is normally not advertised. However, you will see this service once connected to the peripheral with [-CBPeripheral discoverServices:].
As a side note, just a minor Objective-C reminder:
You can use initializer syntax to reduce the verbosity of your code:
[self.centralManager
scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:DEVICE_INFO_SERVICE_UUID]]
options:nil];
This code works for me (when scanning for devices with service @"feff")
#define MY_SERVICE_UUID_STR @"feff"
CBUUID *myUUID = [CBUUID UUIDWithString:MY_SERVICE_UUID_STR];
[self.CM scanForPeripheralsWithServices:[NSArray arrayWithObject:myUUID] options:nil];
In this code I don't terminate with nil and only have 1 service in the list.
Are you checking that the central manager is powered up?
if (self->CM.state != CBCentralManagerStatePoweredOn)
{
printf("CoreBluetooth not correctly initialized !\n");
printf("State = %d (%s)\r\n",
self->CM.state,[self centralManagerStateToString:self.CM.state]);
return -1;
}