我试图创建一个简单的蓝牙LE外设连接到一个预先存在的中央。从我可以告诉,我的外围设备管理器设置正确,并开始投放广告的呼叫与正确的服务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
s,而不是一个单一CBUUID
的阵列;
let adData = [CBAdvertisementDataLocalNameKey : "MackJohn_Bluetooth_On_iOS", CBAdvertisementDataServiceUUIDsKey : [SERVICE_UUID]] as [String : Any]