how to connect with bluetooth low energy in ios swift?

时光怂恿深爱的人放手 提交于 2019-12-01 05:04:43

问题


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> 

回答1:


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




回答2:


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




回答3:


      @IBAction func btnConnect(_ sender: UIButton){          self.appDelegate.bleManager.stopScan()          self.appDelegate.selectPeripheral = self.arrayPeripheral[sender.tag]          self.appDelegate.bleManager.connect(self.selectPeripheral, options: nil)        } 


来源:https://stackoverflow.com/questions/43358925/how-to-connect-with-bluetooth-low-energy-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!