Swift 中无法将 BLE 广告数据转换为字符串

Cannot convert BLE advertisement data to String in Swift

我正在使用标准的 CentralManager 调用在没有连接的情况下获取一些 BLE 广告数据。 我的代码片段是:

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 = ""
        }
....
}

打印行产生

ManufacturerData 的值为 Optional(<3235343a 3834>)

它显示了我想要的 2 个整数值 254:84 所以我知道这些值在那里。 我找不到以某种形式获取 manufacturerData 以开始提取 2 个值的方法。 'manufacturerData =' 行的错误是

无法将类型“UTF8.Type”(又名“Unicode.UTF8.Type”)的值转换为预期的参数类型“String.Encoding”

manufacturerData = String(data: mData as! Data, encoding: UTF8.self)

应该是

manufacturerData = String(data: mData as! Data, encoding: .utf8)

现在,为了避免强制展开,您可以这样做:

if let mData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
    manufacturerData = String(data: mData, encoding: .utf8)
}

manufacturerData 那么会是 "254:84"

由此,您可以使用 components(separatedBy:):

let components = manufacturerString.components(separatedBy: ":")
let first = components[0] //"254"
let second = components[1] //"84"