0

我是iOS的核心蓝牙编程的新手。最近我遇到了这个问题,当连接到外设时,屏幕上会弹出“蓝牙配对请求”提示。但是,如果不管我取消请求,输入无效PIN码,或者干脆什么也不做,CBPeripheral始终连接到CBCentralManager,即使配对请求不成功

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

委托总是被调用。这意味着连接总是成功。谁能解释为什么会发生这种情况?谢谢。

回答

0

连接到外设将触发(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;,因此如果BLE设备启用了配对,您将收到提示询问配对的提示。如果配对不成功,如果设备在配对失败后没有断开连接的命令,它将保持连接状态,但如果尝试发现其服务(*)和特性,则可能无法获得任何连接(取决于固件BLE设备的一侧已配置)。

- (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]; 
    } 
} 
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) 
       } 
      } 
    } 
相关问题