macOS CBCentralManager状态不受支持

问题描述 投票:0回答:1

我试图在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()

  }

  ...

}

这将持续输出Unsupported,并带有控制台警告

[CoreBluetooth] XPC connection invalid

我知道Info.plist密钥NSBluetoothPeripheralUsageDescription,我尝试过,但我相信这只适用于iOS设备。

我是否在寻找在iMac上管理蓝牙的错误方向?或者我的实现缺少什么?我觉得我已经涵盖了Core Bluetooth documentation所需的一切。

swift macos bluetooth core-bluetooth
1个回答
4
投票

我相信这是因为启用了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>    
© www.soinside.com 2019 - 2024. All rights reserved.