无法从iOS检索配对的外围设备列表。也无法检查特定外围设备是否已配对。
有两种情况需要考虑:
外围设备可能已经连接在系统中(iOS会自动连接某些外围设备,以便例如显示电池电量)。在这种情况下,外围设备不会广播,并且使用scanForPeripherals
进行检测将无法工作。
外围设备已配对,但未连接。在这种情况下,retrieveConnectedPeripherals(withServices:)
将无法工作。
因此,要检索您的外围设备,您需要结合这两个方面。首先,您需要检查它是否在从retrieveConnectedPeripherals(withServices:)
返回的外围设备中。如果没有,您应该使用scanForPeripherals
。
如果您想检索超出范围的外围设备,则可以尝试使用retrievePeripherals(withIdentifiers:)
,但它也可能返回未配对的设备,并且依赖于外围设备的UUID
,您必须在配对后保存。
有一种方法可以检测特定外围设备是否已配对。您需要尝试从受保护的特征(需要加密 - 绑定)中读取数据。如果收到预期的数据,则表示用户接受了配对请求。否则,您将收到空响应或无响应。
您可以在我的文章中阅读更多关于蓝牙的信息:
如果您正在将经典蓝牙连接到MFi设备上,可以使用ShowBluetoothAccessoryPicker
。
EAAccessoryManager.SharedAccessoryManager.ShowBluetoothAccessoryPicker(null, completion: ((Foundation.NSError error) => {
Console.WriteLine("My callback");
if (error != null && (uint)error.Code != (uint)EABluetoothAccessoryPickerError.AlreadyConnected)
{
Console.WriteLine(String.Format("Error code: {0} Desc: {1}", error.Code, error.DebugDescription));
Console.WriteLine("Failed? " + EABluetoothAccessoryPickerError.Failed.ToString());
Console.WriteLine("Failed? " + Convert.ToInt64(EABluetoothAccessoryPickerError.Failed));
}
}));
你需要找到你感兴趣的服务UUID,在我的情况下它完美地工作。
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]
options:options];
当它发现任何广告相同服务UUID的设备时,它将出现在您上面指定的屏幕上。
以这种方式处理didDiscoverperipherel:
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
_discoveredPeripheral = peripheral;
if(![self.mRemoteDevices containsObject:_discoveredPeripheral])
{
NSArray *peripherels = [self.centralManager retrievePeripheralsWithIdentifiers:@[_discoveredPeripheral.identifier]];
[self.mRemoteDevices addObject:[peripherels objectAtIndex:0]];
}
}