【问题标题】:Get IOBluetoothDevice * from CBPeripheral * (Mac OS X)从 CBPeripheral * 获取 IOBluetoothDevice * (Mac OS X)
【发布时间】:2018-03-07 04:33:21
【问题描述】:
我想知道是否有办法从CBPeripheral * 对象中获取IOBluetoothDevice * 对象,因为我正在制作一个高级蓝牙控制器框架(它将基于IOBluetooth)并且我正在使用它扫描Bluetooth Classic 和Bluetooth Low Energy 设备。以下是一些问题:
IOBluetooth 确实允许您搜索这两个网络,但由于某种原因,它没有显示CoreBluetooth 所在的所有Bluetooth Low Energy 设备。
如果我使用CoreBluetooth 搜索Bluetooth Low Energy 设备,我将无法获得我以后使用所需的地址。
那么有什么方法可以从CBPeripheral 获取IOBluetoothDevice 对象?
谢谢:D
【问题讨论】:
标签:
bluetooth
core-bluetooth
iobluetooth
【解决方案1】:
我发现我可以搜索 /Library/Preferences/com.apple.bluetooth.plist > CoreBluetoothCache,它恰好包含 UUID 并且在它的字典中 DeviceAddress = 地址 ;)。
所以我可以通过使用方法获取CBPeripheral 的 UUID
NSString *uuid = [[<*CBPeripheral*> identifier] UUIDString];
然后在属性列表中查找
NSDicionary *btdict = [NSDictionary dictionaryWithContentsOfFile:@"/Library/Preferences/com.apple.bluetooth.plist"];
NSDictionary *bleDevices = [btDict objectForKey:@"CoreBluetoothCache"];
NSString *address = [[bleDevices objectForKey:uuid] objectForKey:@"DeviceAddress"];
然后使用该地址创建一个新的 IOBluetoothDevice:
IOBluetoothDevice *device = [IOBluetoothDevice deviceWithAddressString:address];
就这么简单:D
【解决方案2】:
Swift 5.3 解决方案:
fileprivate func getDeviceAddress(for cbPeripheral: CBPeripheral) -> String?
{
if let userDefaults = UserDefaults(suiteName: "/Library/Preferences/com.apple.Bluetooth")
{
if let coreBluetoothCache = userDefaults.object(forKey: "CoreBluetoothCache") as? [String : Any]
{
if let deviceData = coreBluetoothCache[cbPeripheral.identifier.uuidString] as? [String : Any]
{
return deviceData["DeviceAddress"] as? String
}
}
}
return nil
}
用法:
if let deviceAddress = self.getDeviceAddress(for: peripheral)
{
if let bluetoothDevice = IOBluetoothDevice(addressString: deviceAddress)
{
// Do your stuff
}
}