Definir notificações em características resulta em erro de identificador inválido
Usando o CoreBluetooth Quero enviar dados do iPhone para o Mac. Para isso, escrevi códigos como o iPhone como 'Peripheral' e Mac como 'Central'.
Funciona perfeitamente, mas às vezes desconecta diretamente e, em seguida, conecta e desconecta continuamente.
Algumas vezes, quando está tentando se reconectar, no Central chama diretamente o método de delegação 'didDisconnectPeripheral'. Mas algumas vezes há o erro "O identificador é inválido" em 'didUpdateNotificationStateForCharacteristic'.
Consultei todos os links na net. Mas não sou capaz de resolver esse problema. Eu pensei que no iPhone estava armazenando cache Bluetooth.
Por favor, sugira uma solução como resolver o erro "O identificador é inválido"?
Abaixo estão alguns dos métodos importantes.
Para Peripheral, escrevi Code como abaixo.
No Appdelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.peripheral = [[PeripheralServerObject alloc] init];
self.peripheral.serviceUUID = [CBUUID UUIDWithString:@"4w24"];
return YES;
}
No arquivo de objeto periférico:
//To Check Bluetooth State
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBPeripheralManagerStatePoweredOn:
[self enableService];
break;
case CBPeripheralManagerStatePoweredOff: {
[self disableService];
break;
}
}
// To Add characteristics to Service
- (void)enableService
{
[self.peripheral removeAllServices];
self.service = [[CBMutableService alloc]
initWithType:self.serviceUUID primary:YES];
self.authChar =
[[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:@"a86e"]
properties:CBCharacteristicPropertyNotify
value:nil
permissions:CBAttributePermissionsReadable];
self.respChar =
[[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:@"a86f"]
properties:CBCharacteristicPropertyWriteWithoutResponse
value:nil
permissions:CBAttributePermissionsWriteable];
self.service.characteristics = @[ self.authChar, self.respChar ];
// Add the service to the peripheral manager.
[self.peripheral addService:self.service];
}
//Peripheral Manager delegate method will be called after adding service.
- (void)peripheralManager:(CBPeripheralManager *)peripheral
didAddService:(CBService *)service
error:(NSError *)error {
[self startAdvertising];
}
//To disable service
- (void)disableService
{
[self.peripheral stopAdvertising];
[self.peripheral removeAllServices];
}
//To enable a service again.
-(void)refreshService {
[self disableService];
[self enableService];
}
If central subscribes the characteristic, then the below peripheral delegate method will be called. In this I implemented code to send data
- (void)peripheralManager:(CBPeripheralManager *)peripheral
central:(CBCentral *)central
didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
self.dataTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(sendData)
userInfo:nil
repeats:YES];
}
- (void)sendData
{
Here I am sending data like [Apple's BTLE Example Code][1]
}
//If unsubscribed then I am invalidating timer and refreshing service
- (void)peripheralManager:(CBPeripheralManager *)peripheral
central:(CBCentral *)central
didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
if (self.dataTimer)
[self.dataTimer invalidate];
[self refreshService];
}
Para Mac, escrevi métodos delegados periféricos.
//I enables the notification for "a860" Characteristic.
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
error:(NSError *)error {
CBUUID * authUUID = [CBUUID UUIDWithString:@"a86e"];
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:authUUID]) {
}
[self.connectedPeripheral setNotifyValue:YES
forCharacteristic:characteristic];
}
}
-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
Here I am getting error sometimes "The handle is invalid".
}
}