0

I am wondering if there is a way i can get an IOBluetoothDevice * object from a CBPeripheral * object because I am making an advanced bluetooth controller framework (Its going to be based on IOBluetooth) and Im using it so scan for Bluetooth Classic and Bluetooth Low Energy devices. Here are some of the problems:

  1. IOBluetooth does allow you to search for both networks but for some reason its not showing up all of the Bluetooth Low Energy Devices that CoreBluetooth is.

  2. If I use CoreBluetooth to search for Bluetooth Low Energy Devices I won't be able to get the address which I require for later use.

So is there any way i can get an IOBluetoothDevice object from a CBPeripheral?

thanks :D

4

2 回答 2

4

我发现我可以搜索/Library/Preferences/com.apple.bluetooth.plist > CoreBluetoothCache恰好包含 UUID 并且在其字典中DeviceAddress= 地址 ;)。

CBPeripheral所以我可以通过使用方法来获取 a 的 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

于 2018-03-20T06:27:44.957 回答
1

斯威夫特 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
    }
}
于 2021-02-06T14:55:31.030 回答