how to connect with bluetooth low energy in ios sw

2020-03-24 08:13发布

I want to connect with ble peripheral. But my code doesn't call didConect function

this is my code :

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)
    }

Logs :

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

3条回答
在下西门庆
2楼-- · 2020-03-24 08:15

I created a demo project, which scans for Bluetooth LE devices and displays them in a list:

Check it out on github: quickies/BluetoothScanner.ios

Screenshot

Screenshot

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-03-24 08:20
      @IBAction func btnConnect(_ sender: UIButton){

        self.appDelegate.bleManager.stopScan()

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

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

      }
查看更多
ら.Afraid
4楼-- · 2020-03-24 08:36

I've solved this.
just need to change :

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

into this :

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

reference : Swift 3: Can't connect to peripheral via BLE

查看更多
登录 后发表回答