I scan for my peripheral like this:
NSDictionary *scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
// Scan for peripherals with given UUID
[cm scanForPeripheralsWithServices:[NSArray arrayWithObject:HeliController.serviceUUID] options:scanOptions]
No problem there, I find the peripheral and are able to connect to it. As you can see I give it CBCentralManagerScanOptionAllowDuplicatesKey
with bool NO
to not allow for more than one peripheral, but sometimes the didDiscoverPeripheral
callback fires twice.
- (void) centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI
{
if(!discovered){
discovered = YES;
NSLog(@"Discovered");
[cm stopScan];
[scanButton setTitle:@"Connect" forState:UIControlStateNormal];
}
else if(discovered){
discovered = YES
NSLog(@"Already discovered");
}
}
Some times I get
Discovered
Already discovered
as output in my console, and most of the times only the Discovered
message shows.
In my peripheral delegate I first discover services, which then call [peripheral discoverCharacteristics
and the callback always occurs:
- (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
NSLog(@"Did discover characteristic for service %@", [service.peripheral UUID]);
for(CBCharacteristic *c in [service characteristics]){
// We never get here when peripheral is discovered twice
if([[c UUID] isEqual:myCharacteristicUUID]){
NSLog(@"Found characteristic");
self.throttleCharacteristic = c;
}
}
When didDiscoverPeripheral
occur twice, service
becomes nil
in this method, even though peripheral
is not (UUID, name is still correct).
Rebooting the phone or resetting the network settings fixes the problem temporarily.
I really need to get this fixed! Thank you
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…