I am using a standard CentralManager call to get some BLE advertisement data without connecting. My code snippet is:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("The value of ManufacturerData is \(String(describing: advertisementData[CBAdvertisementDataManufacturerDataKey]))")
var manufacturerData: String!
if let mData = advertisementData[CBAdvertisementDataManufacturerDataKey] {
manufacturerData = String(data: mData as! Data, encoding: UTF8.self)
}
else {
manufacturerData = ""
}
....
}
The print line produces
The value of ManufacturerData is Optional(<3235343a 3834>)
which shows the 2 integer values I want as 254:84 so I know that the values are there. I can't find a way to get the manufacturerData in a form to start extracting the 2 values. The error on the 'manufacturerData =' line is
Cannot convert value of type ‘UTF8.Type’ (aka ‘Unicode.UTF8.Type’) to expected argument type ’String.Encoding’
CodePudding user response:
manufacturerData = String(data: mData as! Data, encoding: UTF8.self)
should be
manufacturerData = String(data: mData as! Data, encoding: .utf8)
Now, to avoid the force unwrap, you could do:
if let mData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
manufacturerData = String(data: mData, encoding: .utf8)
}
manufacturerData
then will be "254:84"
From that, you can use components(separatedBy:)
:
let components = manufacturerString.components(separatedBy: ":")
let first = components[0] //"254"
let second = components[1] //"84"