简体   繁体   English

可以在Cocoa / ObjC中“取消配对”蓝牙设备吗?

[英]Is it possible to “unpair” a Bluetooth device in Cocoa/ObjC?

I've paired an IOBluetoothDevice in my Mac/Cocoa app and would like to "unpair" it programmatically. 我在我的Mac / Cocoa应用程序中配对了一个IOBluetoothDevice ,并希望以编程方式“ IOBluetoothDevice配对”它。 That is, I would like to remove the device from the left pane of the Bluetooth section of System Preferences. 也就是说,我想从“系统偏好设置”的“蓝牙”部分的左侧窗格中删除该设备。

I've seen [IOBluetoothDevice removeFromFavorites] , but that just removes the heart icon next to the "Favorite" attribute of the device -- the device is still listed in the left pane. 我见过[IOBluetoothDevice removeFromFavorites] ,但只是删除了设备“收藏夹”属性旁边的心脏图标 - 设备仍然在左窗格中列出。

Is this possible through Cocoa? 这可能通过Cocoa吗?

系统偏好设置的蓝牙部分

In the above picture, I would like to programmatically remove "Apple Mighty Mouse" from the left pane. 在上图中,我想以编程方式从左侧窗格中删除“Apple Mighty Mouse”。

Paired devices are a part of System Preferences. 配对设备是“系统偏好设置”的一部分。

You can find the file with the bluetooth preferences in /Library/Preferences , its name is com.apple.Bluetooth.plist . 您可以在/Library/Preferences找到带有蓝牙首选项的文件,其名称为com.apple.Bluetooth.plist

com.apple.Bluetooth.plist

However, you cannot edit the file directly. 但是,您无法直接编辑该文件。 You should use SCPreferences class from System Configuration framework. 您应该使用System Configuration框架中的SCPreferences类。

Note the API for accessing/modifying system preferences is pretty low level. 请注意,用于访问/修改系统首选项的API非常低级别。

EDIT: The following code works if run in superuser mode. 编辑:如果在超级用户模式下运行,以下代码可以正常工作。 I am not a Mac OS developer myself but it should be possible to init it with an AuthorizationRef and run it with user mode (the user will confirm access to system configuration). 我自己不是Mac OS开发人员,但应该可以使用AuthorizationRef启动它并使用用户模式运行它(用户将确认访问系统配置)。

SCPreferencesRef prefs = SCPreferencesCreate(kCFAllocatorDefault,
                                             CFSTR("Test"),
                                             CFSTR("/Library/Preferences/com.apple.Bluetooth.plist"));

const CFStringRef PAIRED_DEVICES_KEY = CFSTR("PairedDevices");

NSArray *pairedDevices = (__bridge NSArray *) SCPreferencesGetValue(prefs, PAIRED_DEVICES_KEY);

NSLog(@"Paired devices: %@", pairedDevices);

NSString *deviceToRemove = @"e4-32-cb-da-ca-2f";        

NSMutableArray *newPairedDevices = [pairedDevices mutableCopy];
[newPairedDevices removeObject:deviceToRemove];

Boolean valueSet = SCPreferencesSetValue(prefs, PAIRED_DEVICES_KEY, (__bridge CFPropertyListRef) [NSArray arrayWithArray:newPairedDevices]);

NSLog(@"Value set: %@", (valueSet) ? @"YES" : @"NO");

if (!valueSet) {
    NSLog(@"Error: %@", SCCopyLastError());
}

Boolean saved = SCPreferencesCommitChanges(prefs);

if (!saved) {
    NSLog(@"Error: %@", SCCopyLastError());
}

NSLog(@"Saved: %@", (saved) ? @"YES" : @"NO");

CFRelease(prefs);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM