如何在ios swift中使用蓝牙低能耗连接?
我想连接外设。 但我的代码不调用didConect函数 这是我的代码:如何在ios swift中使用蓝牙低能耗连接?,ios,swift,bluetooth-lowenergy,beacon,Ios,Swift,Bluetooth Lowenergy,Beacon,我想连接外设。 但我的代码不调用didConect函数 这是我的代码: func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { let device = (advertisementData as NSDictionary) .object
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>
BLE服务已通电
你发现了外设吗
我已经解决了这个问题。只需要改变一下:
func centralManager(central: CBCentralManager, didConnect peripheral: CBPeripheral)
为此:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)
参考资料:我创建了一个演示项目,该项目扫描蓝牙LE设备并将其显示在列表中: 在github上查看它: 截图
您是否确认您的
if
测试通过了?通常,您会保存感兴趣设备的标识符
,而不是查看广告数据。是的。日志打印“确实发现了外围设备”。当我在central.connect之后打印某些内容时,它会打印在日志中。似乎没有执行central.connect。@paulw11如何声明\u peripheral
?如果您的连接失败,您是否实现了didFailToConnect
delegate方法?现在我可以执行函数didConnect peripheral,它失败是因为“”符号。它必须是:func centralManager(central:CBCentralManager,didConnect peripal:cbperipal)感谢您帮助@Paulw11Good查找。在Swift 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)
}