[英]how to connect with bluetooth low energy in ios swift?
I want to connect with ble peripheral.我想连接ble外设。 But my code doesn't call didConect function但是我的代码没有调用 didConect 函数
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>
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参考: Swift 3:无法通过 BLE 连接到外围设备
I created a demo project, which scans for Bluetooth LE devices and displays them in a list:我创建了一个演示项目,它扫描蓝牙 LE 设备并将它们显示在列表中:
Check it out on github: quickies/BluetoothScanner.ios在 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.