- 我搜索并连接我的iPhone与耳机
- 我将设备与iPhone配对
- 我打开我的应用程序,它会搜索蓝牙设备
- 当应用程序找到我的设备时,它会请求连接
- iOS弹出一个消息,要求用户按下“立即配对”按钮以连接设备
--------------- 编辑1 --------- 我稍微改了一下代码。我在第一次连接时保存了设备的UUID,并在重新连接设备时尝试查找“已知外设”并重新连接它。代码实际上找到了“已知外设”,但在我尝试重新连接它之后,它又要求再次配对。是否有办法避免设备重新连接时弹出“立即配对”弹窗?
片段:
-(void) connectToPeripheral : (CBPeripheral*) peripheral {
[self.centralManager stopScan];
self.peripheral = peripheral;
peripheral.delegate = self;
[self.centralManager connectPeripheral:peripheral options:nil];
self.peripheral = peripheral;
}
-(void) searchForDevices {
// Scan for all available CoreBluetooth LE devices
if (self.centralManager == nil ) {
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.centralManager = centralManager;
}
//check if previous peripheral exists
NSArray *knownPeripherals = nil;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* knownPeripheralID = [defaults stringForKey:@"knownPeripheralID"];
if ( knownPeripheralID != nil ) {
self.connectedPeripheralUUID = [[NSUUID alloc] initWithUUIDString:knownPeripheralID];
knownPeripherals = [self.centralManager retrievePeripheralsWithIdentifiers:[NSArray arrayWithObjects:self.connectedPeripheralUUID, nil]];
}
if ( knownPeripherals != nil && [knownPeripherals count] > 0 ) {
NSLog(@"knownPeripherals Peripherals");
CBPeripheral *foundPeripheral = [knownPeripherals objectAtIndex:0];
[self connectToPeripheral:foundPeripheral];
} else {
NSArray *connectedPeripherals = [self.centralManager retrieveConnectedPeripheralsWithServices:[NSArray arrayWithObjects:UUID_SERIAL_SERVICE_STR, nil]];
NSLog(@"Connected Peripherals");
if ( connectedPeripherals != nil && [connectedPeripherals count] > 0 ) {
} else {
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
}
}