iOS CoreBluetooth: startAdvertising() Error advertising static data

怎甘沉沦 提交于 2019-12-05 06:24:18

The value for the CBAdvertisementDataServiceUUIDsKey in the dictionary passed to startAdvertising is an array of CBUUID objects, but you are only passing a single CBUUID. Once I changed it to an array your code worked.

func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {

    if (error != nil) {
        print("PerformerUtility.publishServices() returned error: \(error!.localizedDescription)")
        print("Providing the reason for failure: \(error!.localizedFailureReason)")
    }
    else {
        peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [service.UUID]])
    }
}
user3069232

a few minor points; I have an additional parameter.

peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)

I have this code in peripheralManagerDidUpdateState, right @ the top.

if (peripheral.state != .PoweredOn) {
    return;
}

And I call this within the same method, assuming it is powered on of course.

transferCharacteristic = CBMutableCharacteristic(type: cbtransfer, properties: .Notify, value: nil, permissions: .Readable)
transferService = CBMutableService(type: cbservice, primary: true)
transferService.characteristics = [transferCharacteristic]

Finally I do this:

peripheralManager!.addService(transferService)                    
peripheralManager!.startAdvertising([CBAdvertisementDataServiceUUIDsKey :[cbservice]])

But note; I don't append the characteristics; I use the syntax you see here, appending doesn't work. For reasons I don't clearly understand Swift says its ok, but so it is syntactically good, but BLE doesn't like it.

func publishServices(newService:CBMutableService!) {
    peripheralManager?.addService(newService)
}

Review your code and make the changes; it should work.

The error parameter in the method:

func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?)

Reports the error:

Error Domain=CBErrorDomain Code=1 "One or more parameters were invalid." UserInfo={NSLocalizedDescription=One or more parameters were invalid.}

Issue was needing to pass an array of UUIDs and also use the CBUUID(string:) type rather than UUID(uuidString:). Each issue reproduces the error independently.

struct BluetoothPeripheral {
    let localName: String
    let uuid: String

    func peripheralData() -> [String : Any] {
        return [
            CBAdvertisementDataLocalNameKey    : localName,
            CBAdvertisementDataServiceUUIDsKey : [CBUUID(string: uuid)],
        ]
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!