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

本小妞迷上赌 提交于 2019-12-04 04:39:46

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.

However, you cannot edit the file directly. You should use SCPreferences class from System Configuration framework.

Note the API for accessing/modifying system preferences is pretty low level.

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).

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!