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) 
       } 
      } 
    } 
相關問題