我正在尝试创建一个简单的蓝牙 LE 外围设备以连接到预先存在的 Central。据我所知,我的 Peripheral Manager 设置正确,开始广告的调用已到位且服务 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")
}
最佳答案
你犯了一个小错误; CBAdvertisementDataServiceUUIDsKey
的值应该是CBUUID
的数组,而不是单个CBUUID
;
let adData = [CBAdvertisementDataLocalNameKey : "MackJohn_Bluetooth_On_iOS", CBAdvertisementDataServiceUUIDsKey : [SERVICE_UUID]] as [String : Any]
关于ios - BLE外设不做广告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54584990/