如何在 ios swift 中连接低功耗蓝牙?

how to connect with bluetooth low energy in ios swift?

我想连接蓝牙外设。 但是我的代码没有调用 didConect 函数

这是我的代码:

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
 let device = (advertisementData as NSDictionary)
            .object(forKey: CBAdvertisementDataLocalNameKey)
            as? NSString

        if device?.contains(BEAN_NAME) == true {

            print("Did discover peripheral", peripheral)

            self.bluetoothManager.stopScan()
            self._peripheral = peripheral
            self._peripheral.delegate = self
            central.connect(peripheral, options: nil)
        }
}


func centralManager( central: CBCentralManager, didConnect peripheral: CBPeripheral) { //cant call this
        print("connected to \(BEAN_NAME)")
        peripheral.discoverServices(nil)
    }

日志:

BLE service is powered on
Did discover peripheral <CBPeripheral: 0x1740eef00, identifier = 4872623B-F872-443A-8A96-F4E1F84D6841, name = GoDoor in  :), state = disconnected>

我已经解决了这个问题。
只需要更改:

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

进入这个:

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

参考:

我创建了一个演示项目,它扫描蓝牙 LE 设备并将它们显示在列表中:

在 github 上查看:quickies/BluetoothScanner.ios

截图

      @IBAction func btnConnect(_ sender: UIButton){

        self.appDelegate.bleManager.stopScan()

        self.appDelegate.selectPeripheral = self.arrayPeripheral[sender.tag]

        self.appDelegate.bleManager.connect(self.selectPeripheral, options: nil)

      }