iOSでCoreBluetoothを使用してBluetoothアプリを構築しています。アプリが起動されるたびに、ユーザーは Peripheral の LocalNameKey に保存されている ID を受け取り、それを使用してアドバタイズを開始し、CentralManager を使用して他のユーザーの検索を開始します。すべてのユーザーはローカル名で識別され、それで問題ありません。
CentralManager を使用すると、すべてのユーザーが別のユーザーの Peripheral の特性に値を書き込み、変更について通知することができます。それも機能しています。ここで問題が発生します。接続が完了し、Peripheral が didRecieveWriteRequests メソッドを実行した後、CBPeripheralManager と CBCentralMange の両方がリセットされ、再初期化されます。その後、Peripheral の LocalNameKey は特定の ID ではなく、iPhone の指定された名前または (null) になります。それはアプリの全体的なアイデアを台無しにしますが、私はそれができると確信しています.
Bluetoothをオフにしてオンにすると、再び機能します。
これは、接続後にCentralをクリーンアップする方法です:
- (void)cleanup
{
// See if we are subscribed to a characteristic on the peripheral
if (self.peripheral.services != nil) {
for (CBService *service in self.peripheral.services) {
if (service.characteristics != nil) {
for (CBCharacteristic *characteristic in service.characteristics) {
if (characteristic.isNotifying) {
// It is notifying, so unsubscribe
[self.peripheral setNotifyValue:NO forCharacteristic:characteristic];
// And we're done.
return;
}
}
}
}
}
// If we've got this far, we're connected, but we're not subscribed, so we just disconnect
[self.manager cancelPeripheralConnection:self.peripheral];
}
これは、ブルートゥースのセントラルとペリフェラルを再初期化する方法です:
self.bluetoothPeripheral = nil;
self.bluetoothCentral = nil;
self.bluetoothPeripheral = [[BluetoothPeripheral alloc] initWithID:idNumber];
[self.bluetoothPeripheral loadManager];
self.bluetoothCentral = [[BluetoothCentral alloc] init];