不支持macOS CBCentralManager状态

com*_*ohn 0 macos bluetooth core-bluetooth swift

我正在尝试访问macOS(2017 iMac)上的蓝牙外围设备,但是CBCentralManager似乎从未进入该.poweredOn状态。

import Cocoa
import CoreBluetooth

class BluetoothManager: NSObject {
  var centralManager: CBCentralManager!
  override init() {
    super.init()
    self.centralManager = CBCentralManager(delegate: self, queue:nil)
    self.checkState()
  }

  func checkState() {
    print("central state: \(self.centralManager?.state.rawValue ?? -1)")
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2), execute: {
      self.checkState()
    })
  }
}


extension BluetoothManager: CBCentralManagerDelegate {
  func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
      print("Power on")
    case .unsupported:
      print("Unsupported")
    default:break
    }
  }
}


@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  var bluetoothManager: BluetoothManager?

  func applicationDidFinishLaunching(_ aNotification: Notification) {
    self.bluetoothManager = BluetoothManager()

  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

这将始终输出Unsupported,并带有控制台警告

[CoreBluetooth] XPC connection invalid
Run Code Online (Sandbox Code Playgroud)

我知道我尝试过的Info.plist密钥NSBluetoothPeripheralUsageDescription,尽管我相信这仅适用于iOS设备。

我在iMac上管理蓝牙的方向错误吗?还是我的实现缺少某些东西?我觉得我已经涵盖了Core Bluetooth文档中所需的所有内容

com*_*ohn 5

我相信这是由于已App Sandbox启用(在项目中找到Capabilities)。

启用Bluetooth(在下方Hardware)并接受对权利文件的自动更改,可以解决此问题。

同时也禁用了App Sandbox似乎可行的功能,但是我还不了解该操作是否安全。

作为参考,我的权利文件现在如下所示:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  
<plist version="1.0">   
<dict>  
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.device.bluetooth</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
</dict> 
</plist>    
Run Code Online (Sandbox Code Playgroud)