繁体   English   中英

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

[英]how to connect with bluetooth low energy in ios swift?

我想连接ble外设。 但是我的代码没有调用 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)

参考: Swift 3:无法通过 BLE 连接到外围设备

我创建了一个演示项目,它扫描蓝牙 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)

      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM