我从手机连接到使用该设备的 UUID 和方法绑定的另一台设备
- (NSArray *)retrievePeripheralsWithIdentifiers:(NSArray *)identifiers
来自 CBCentralManager 对象。我在应用程序启动时自动执行此操作。一切正常,我可以使用连接的外围设备发送和接收数据。
然后,如果我超出范围,我就会与设备断开连接。当我回到范围内时,蓝牙会自动连接到绑定的设备,但我的 CBCentralManager 没有。所以我必须通过单击按钮并再次检索连接的外围设备来强制连接。这很烦人,所以我想知道,当先前连接的设备再次连接时,是否有任何方法被调用?或任何设备,不一定是已连接的设备,因为我有 UUID。
有关更多详细信息,我正在使用一个名为的单例类BluetoothHelper
,该类在应用程序启动时进行实例化,并且我有 main CBCentralManager
object @property (strong, nonatomic) CBCentralManager *bluetoothManager;
。我通过以下方式对其进行初始化:
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{ CBCentralManagerOptionRestoreIdentifierKey:@"randomCentralManagerId" }];
在 Singleton 的初始化中。然后,正如您在上面看到的,我在收到中央管理器状态后尝试连接到设备。
-(void)startScanning{
NSString *uuidStr = @"some string i have stored";
NSUUID *identifier = [[NSUUID alloc] initWithUUIDString:uuidStr];
NSArray *connectedDevices = [self.bluetoothManager retrievePeripheralsWithIdentifiers: @[identifier]];
if( connectedDevices.count != 0 ){
NSLog(@"Discovered connected devices");
self.peripheral = [connectedDevices objectAtIndex:0];
[self.bluetoothManager connectPeripheral:self.peripheral options:nil];
}
}
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
if( central.state != CBCentralManagerStatePoweredOn ){
return;
}
if( central.state == CBCentralManagerStatePoweredOn ){
[self performSelector:@selector(startScanning) withObject:nil afterDelay: 0.5];
}
if( central.state == CBCentralManagerStateUnauthorized){
NSLog(@"Unathorized");
}
}
单例类在 AppDelegate 中初始化:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.bluetoothHelper = [BluetoothHelper getInstance];
}