BLE外围非广告

时间:2019-02-08 01:45:10

标签: ios swift bluetooth-lowenergy core-bluetooth

我正在尝试创建一个简单的Bluetooth LE外围设备以连接到预先存在的Central。据我所知,我的外围设备管理器已正确设置,并且使用正确的服务UUID进行了开始广告的调用。但是,当我进行检查以确保外围设备确实在做广告时,我得到了否定的结果

我已经仔细检查了我的UUID,并确保测试设备上的蓝牙已打开。我也在使用物理设备进行测试,而不是模拟器。

以下是用于设置我的外围广告的代码:

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    if peripheral.state == CBManagerState.poweredOn {
        service = CBMutableService.init(type: SERVICE_UUID, primary: true)

        characteristic = CBMutableCharacteristic.init(type: CHARACTERISTIC_UUID, properties: .read, value: nil, permissions: .readable)
        service?.characteristics = [characteristic!]

        peripheralManager?.add(service!)
        peripheralManager?.delegate = self

        let adData = [CBAdvertisementDataLocalNameKey : "MackJohn_Bluetooth_On_iOS", CBAdvertisementDataServiceUUIDsKey : SERVICE_UUID] as [String : Any]

        peripheralManager?.startAdvertising(adData)
    }
}

我在这里检查我的代码是否真的在做广告并得到错误的结果:

func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
    print(peripheral.isAdvertising)
}

我还注意到该函数根本没有调用:

func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
    print("Added Service")
}

1 个答案:

答案 0 :(得分:1)

您犯了一个小错误; CBAdvertisementDataServiceUUIDsKey的值应为CBUUID s的 array ,而不是单个CBUUID;

let adData = [CBAdvertisementDataLocalNameKey : "MackJohn_Bluetooth_On_iOS", CBAdvertisementDataServiceUUIDsKey : [SERVICE_UUID]] as [String : Any]