1

I am new to Core Bluetooth programming in iOS. Recently I encountered this problem that when connecting to a peripheral, "Bluetooth Pairing Request" alert will pop up on screen. But regardless if I cancelled the request, entered an invalid pin, or simply do nothing,

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

delegate always gets called. That means connection always succeeds. Anyone who can explain why this happens? Thanks.

caribbean
  • 748
  • 1
  • 9
  • 29

2 Answers2

0

To connect to a peripheral will trigger (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral; so if the BLE device has the pairing enabled you will get the prompt asking for pairing. In case the pairing is unsuccessful, if the device doesn't have a command to disconnect after unsuccessful pairing it will remain connected, BUT if you try to discover its services (*) and characteristics you'll probably get none (depending how the firmware side of the BLE device has been configured).

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Did connect to peripheral: %@", peripheral);

    [peripheral setDelegate:self];
    [peripheral discoverServices:nil];   //* discover peripheral services
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
for (CBService *service in peripheral.services) {
        NSLog(@"discovered service [%@]",service.UUID);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
Pau Senabre
  • 4,155
  • 2
  • 27
  • 36
0

swift 3

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){

           self.bleManager.stopScan()
           peripheral.discoverServices(nil)
    }
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {

          self.displayToastMessage("Fail to connect")
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){

        if let er = error{
            self.displayToastMessage(er as! String)
            return
        }
        if let services = peripheral.services as [CBService]!{
            print(services)
        }
    }
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?){

            if let arraychar = service.characteristics as [CBCharacteristic]!{

                 for getCharacteristic in arraychar{

                      print(getCharacteristic)
                 }
            }
    }
Deepak Tagadiya
  • 2,187
  • 15
  • 28