1

そのデバイスのUUIDとメソッドを使用して、電話から結合された別のデバイスに接続します

- (NSArray *)retrievePeripheralsWithIdentifiers:(NSArray *)identifiers

CBCentralManager オブジェクトから。アプリケーションの起動時にこれを自動的に行います。すべて正常に動作し、接続した周辺機器でデータを送受信できます。

その後、範囲外になると、デバイスから切断されました。範囲内に戻ると、Bluetooth はボンディングされたデバイスに自動的に接続しますが、CBCentralManager は接続しません。そのため、ボタンをクリックして、接続されている周辺機器を再度取得して、接続を強制する必要があります。これはかなり面倒なので、以前に接続されていたデバイスが再び接続されたときに呼び出されるメソッドはありますか? または、UUID を持っているので、必ずしも接続されているとは限らない任意のデバイス。

詳細についてはBluetoothHelper、アプリの起動時にインスタンス化するというシングルトン クラスを使用しており、そこに main CBCentralManagerobjectがあります@property (strong, nonatomic) CBCentralManager *bluetoothManager;。私はそれを初期化します:

self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{ CBCentralManagerOptionRestoreIdentifierKey:@"randomCentralManagerId" }];

シングルトンの初期化で。次に、上記のように、中央マネージャーの状態を受け取った後、デバイスに接続しようとします。

-(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];
}
4

0 に答える 0