CoreBluetooth XPC连接无效。

39
public class BLE: NSObject, CBCentralManagerDelegate {

    var centralManager:CBCentralManager!

    public override init() {
        super.init()
        self.centralManager = CBCentralManager.init(delegate: self, queue: nil)
    }

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {

        switch central.state {
        case .unknown:
            print("unknown")
        case .resetting:
            print("resetting")
        case .unsupported:
            print("unsupported")
        case .unauthorized:
            print("unauthorized")
        case .poweredOff:
            print("powered off")
        case .poweredOn:
            print("powered on")
            self.centralManager.scanForPeripherals(withServices: nil, options: nil)
        }
    }
}

这是我的代码,每当我运行它时,它会给我一个消息:

"[CoreBluetooth] XPC连接无效"

我尝试将NSBluetoothPeripheralUsageDescription添加到我的info.plist文件中,但没有起作用。

奇怪的是,如果我直接初始化CBCentralManager而不使用类,则一切正常。

只有当我尝试通过创建BLE或任何其他类的对象来初始化CBCentralManager时,才会出现此问题。


你有检查过这个网址吗?https://dev59.com/alcP5IYBdhLWcg3ww8qS - aBilal17
你需要在你的info.plist文件中添加一些关键字来解决这个问题。 - aBilal17
1
尝试在您的appDelegate中定义CBCentralManager,在您的BLE类中使用相同的CBCentralManager。 - aBilal17
我在提问之前已经访问过那个网址,这也是我首先尝试编辑我的info.plist的原因。也许您能更具体地指出应添加哪些键? - Zeryx
我也尝试在我的 appDelegate 中定义 CBCentralManager,但不幸的是没有成功。 - Zeryx
5个回答

35

CBCentralManager引用应作为类的成员变量强引用。它不能作为局部引用工作。

尝试下面:

class ViewController: UIViewController {
   var ble: BLE!
   override func viewDidLoad() {
      super.viewDidLoad()

      ble = BLE()
  }
}

class BLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
   private var manager: CBCentralManager!

   required override init() {
      super.init()
      manager = CBCentralManager.init(delegate: self, queue: nil)
   }

   func centralManagerDidUpdateState(_ central: CBCentralManager) {
      var consoleLog = ""

      switch central.state {
      case .poweredOff:
          consoleLog = "BLE is powered off"
      case .poweredOn:
          consoleLog = "BLE is poweredOn"
      case .resetting:
          consoleLog = "BLE is resetting"
      case .unauthorized:
          consoleLog = "BLE is unauthorized"
      case .unknown:
          consoleLog = "BLE is unknown"
      case .unsupported:
          consoleLog = "BLE is unsupported"
      default:
          consoleLog = "default"
      }
      print(consoleLog)
   }
}

18

我遇到了同样的问题:沙盒默认开启,禁用了对蓝牙的访问。

请确保您的目标能力允许蓝牙硬件访问(请参见附加的屏幕截图)。 目标能力


我也没有看到那个应用程序沙盒部分。 - Anonymous-E
查看后台模式 - LAD
2
在XCode中,这已经不再有效。 - Hashim Akhtar
2
谢谢!在Xcode 11中对我有用 - 现在它在“签名和能力”下。 - Ashald

13

对于运行iOS模拟器的人来说,在其中蓝牙是不起作用的。因此,如果你尝试使用蓝牙模拟应用程序,它会引发“[CoreBluetooth] XPC连接无效”错误。

更多信息请参见:https://www.browserstack.com/test-on-ios-simulator

你需要在真实设备上测试你的应用。


3
在我的情况下,结果表明我调用Scan的时间太早了。我是从ViewDidLoad方法中发起调用的。如果我通过按一个按钮来启动扫描,则扫描将正常工作。
我使用的解决方法是在从ViewDidLoad方法调用扫描时使用performSelector与延迟一起使用。

-4

我在我的管理类中解决了将NSObject更改为UIViewController


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接