scanForPeripheralsWithServices:options: unable to connect when specifying services

对着背影说爱祢 提交于 2019-12-07 06:10:44

问题


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?


回答1:


[-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];



回答2:


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;
}


来源:https://stackoverflow.com/questions/22889321/scanforperipheralswithservicesoptions-unable-to-connect-when-specifying-servic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!