BlackHatSamurai
BlackHatSamurai

Reputation: 23483

Bluetooth Pairing vs. Connection in Objective C

I am building an iOS app that connects to a bluetooth unit and I'm noticing that once when it is "connected" I am able to use the delegate method didDiscoverServices; however, when I go through and actually "pair" the bluetooth unit (an alert box pops up and asks to allow unit to pair to phone), I am no longer able to use the didDiscoverServices method, or other methods associated with the CBPeripheral.

I get the "pairing" option when I call the readValueForCharacteristic method. It is then that I get the "pairing" request. After I pair, I am not able to explore the units characteristics or services.

Here is the relevant code:

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{

    for (CBService *service in peripheral.services) {
        NSLog(@"Discovered service %@", service.UUID);
        [services addObject:service.UUID];
        [peripheral discoverCharacteristics:nil forService:service];

    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{

    for (CBCharacteristic *characteristic in service.characteristics) {

        NSLog(@"Discovered characteristic:  %@", characteristic.UUID);
        NSLog(@"Discovered characteristic Properties:  %@", characteristic.service);

        [peripheral readValueForCharacteristic:characteristic];
    }

} 

Upvotes: 1

Views: 2493

Answers (1)

Paulw11
Paulw11

Reputation: 114856

Pairing is initiated when you read/write a characteristic that requires encryption. The pairing process establishes a new connection using the newly exchanged keys, which interrupts the discovery process.

The solution is to complete the discovery of services and characteristics before attempting the read operation.

Upvotes: 4

Related Questions