从 Swift 以编程方式打开 MacOS 的 MIDI 蓝牙配置面板

Open MIDI Bluetooth Configuration pane of MacOS programatically from Swift

我可以像这样以编程方式打开 Audio MIDI Setup 应用程序:

NSWorkspace.shared.launchApplication("Audio MIDI Setup")

但是如何打开应用程序中的 Bluetooth Configuration window?

我看到其他应用程序有一个菜单项可以直接打开这个对话框。

Apple 提供了一个 window 控制器供开发人员使用,名为 CABTLEMIDIWindowController。文档非常稀疏,但代码注释中有更多信息:

/**
@class CABTLEMIDIWindowController

@abstract  A window controller object that can present a window that displays nearby
 Bluetooth-based MIDI peripherals. The user can select one of those peripherals and 
 pair it with their mac. Additionally, the user can advertise the mac as a 
 Bluetooth-based MIDI peripheral.
 
@discussion To use this class, create an instance of the CABTLEMIDIWindowController,
 initialize it, and call showWindow: to display the UI.
*/

用法非常简单:

let windowController = CABTLEMIDIWindowController()
windowController.showWindow(self)

注意:

您的应用必须配置并批准蓝牙,否则 window 控制器将如下所示:

您必须从 App Sandbox 设置 select 蓝牙并将 NSBluetoothAlwaysUsageDescription 键添加到您的 Info.plist:

完整示例:

import Cocoa
import CoreBluetooth
import CoreAudioKit

class ViewController: NSViewController, CBCentralManagerDelegate {
    fileprivate var centralManager: CBCentralManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if (central.state == .poweredOn) {
            let windowController = CABTLEMIDIWindowController()
            windowController.showWindow(self)
        }
    }
}

奖金:

在四处窥探时发现了这个。通过打开系统偏好设置 -> 安全和隐私 -> 隐私 -> 蓝牙,为用户节省大量点击次数:

NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Bluetooth")!)