我像这样扫描我的外围设备:
NSDictionary *scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
forKey:CBCentralManagerScanOptionAllowDuplicatesKey];
// Scan for peripherals with given UUID
[cm scanForPeripheralsWithServices:[NSArray arrayWithObject:HeliController.serviceUUID] options:scanOptions]
没问题,我找到了外围设备并能够连接到它。正如你所看到的,我给它CBCentralManagerScanOptionAllowDuplicatesKey
不允许bool NO
超过一个外围设备,但有时didDiscoverPeripheral
回调会触发两次。
- (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");
}
}
有时我得到
Discovered
Already discovered
作为我的控制台中的输出,并且大多数时候只Discovered
显示消息。
在我的外围委托中,我首先发现服务,然后调用[peripheral discoverCharacteristics
并且总是发生回调:
- (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;
}
}
当didDiscoverPeripheral
出现两次时,service
变成nil
在这个方法中,即使peripheral
不是(UUID,名称仍然正确)。
重新启动手机或重置网络设置可以暂时解决问题。
我真的需要解决这个问题!谢谢