在BLE连接后没有调用didDiscoverServices

时间:2018-03-15 17:12:10

标签: swift xcode bluetooth-lowenergy core-bluetooth

我正在使用我需要验证的BLE设备。我正在使用的BLE代码位于

之下
//Pragma Bluetooth Methods
func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        central.scanForPeripherals(withServices: nil, options: nil)
    } else {
        print("Bluetooth not available.")
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
    if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
        if peripheralName == "test-device1" {
            self.manager.stopScan()

            self.peripheral = peripheral
            self.peripheral.delegate = self

            self.manager.connect(peripheral, options: nil)
        }
    }

}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.discoverServices(nil)
}

private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    for service in peripheral.services! {
        let thisService = service as CBService

        if service.uuid == SERVICE_UUID {
            peripheral.discoverCharacteristics(
                nil,
                for: thisService
            )
        }
    }
}

该过程遵循预期路线,通过didDiscover并将名称验证为“test-device1”。但是,虽然它通过didConnect方法并运行peripheral.discoverServices(nil),但它永远不会到达didDiscoverServices方法。我已经多次介入它,它总是停在didConnect()。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

来自doc的方法:

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?)

此致:

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: Error?)

删除它并重写它,让XCode自动完成功能可以帮助您,从文档中复制/粘贴它,或者只添加一个缺少的_

该方法是可选的,内部CoreBluetooth框架检查委托是否响应选择器(respondsToSelector())并且选择器包括" _"你没有的。所以它不会匹配,因为它不一样,所以不会打电话给它。

答案 1 :(得分:0)

如果这不起作用

func peripheral(_ peripheral:CBPeripheral,didDiscoverServices错误:错误?)

然后首先尝试使用BLE扫描仪iOS扫描BLE设备,如果在该应用程序中它显示服务然后在您的代码中出现问题,否则如果BLE扫描仪显示0服务然后问题在外围设备内, 或者您可以在连接到外围设备后使用print(peripheral.services)检查服务,如果它打印为nil,则发现未调用的服务,否则调用它。

或者您可以在存储到缓存中的数据中重启iPhone。

相关问题