我这样扫描我的外设:
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
方法发生两次时,即使peripheral
仍然存在(UUID和名称仍然正确),在该方法中service
会变成nil
。
重新启动手机或重置网络设置可以暂时解决这个问题。
我真的需要解决这个问题!谢谢。