【问题标题】:Swift: [CoreBluetooth] XPC connection invalid after dismissing popover controllerSwift:[CoreBluetooth] XPC 连接在关闭弹出控制器后无效
【发布时间】:2020-11-02 16:16:33
【问题描述】:

我有 2 个 ViewController(ViewController 和 SecondViewController)。

SecondViewController 是一个 tableView,呈现为 popover。 tableView 将列出所有发现的 BLE 设备,当用户点击单元格时,它将连接到选定的设备。

在用户关闭弹出框之前一切正常,当弹出框关闭时将立即打印以下错误。 [CoreBluetooth] XPC 连接无效

我正在使用协议委托来传递外围设备和特征

这就是我在 SecondViewController 中的内容:

protocol PassDataDelegate {

    func passPeripheral(_ deviceToConnect: CBPeripheral!)

    func passCharacteristic(_ char: CBCharacteristic!)
}

class SecondViewController: UIViewController, CBPeripheralDelegate {
    ...
    var peripherals = Array<CBPeripheral>()
    var deviceToConnect: CBPeripheral?
    var char: CBCharacteristic?
    var deviceReady: Bool?
    var delegate: PassDataDelegate?
...
}

//passing variables
delegate?.passPeripheral(deviceToConnect!)
delegate?.passCharacteristic(char!)

这就是我的 ViewController 中的内容:

extension ViewController: PassDataDelegate {
    func passPeripheral(_ device: CBPeripheral!) {
        self.device = device
    }

    func passCharacteristic(_ characteristic: CBCharacteristic!) {
        self.characteristic = characteristic
        self.deviceReady = true
    }
}

在我的 ViewController 的某个地方,我在 If 语句中使用了 deviceReady。但它表明 Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

好像没有调用协议函数?

请问我可以帮忙吗?

【问题讨论】:

  • SecondViewController 解散后是否取消初始化?我认为delegate 应该是weak 属性。
  • @vpoltave 不,它没有取消初始化。感谢您的评论,您对如何从 popover 传递外设和特性有什么想法吗?
  • 您能说明您分配此var delegate: PassDataDelegate? 属性的位置吗?

标签: ios swift xcode core-bluetooth


【解决方案1】:

我的解决方案有点简单。我只是将我的 ViewController 设置为静态,然后为外围属性创建一个 setter 函数,然后在 SecondViewController 中调用 setter 函数。现在可以了!!

在 ViewController 中:

static var vc: ViewController?
...

func setCB(centralManager: CBCentralManager, deviceToConnect: CBPeripheral, char: CBCharacteristic, deviceReady: Bool) {
    self.centralManager = centralManager
    self.deviceToConnect = deviceToConnect
    self.char = char
    self.deviceReady = deviceReady
}

在 SecondViewController 中:

if let controller = ViewController.vc {
                controller.setCB(centralManager: centralManager, deviceToConnect: deviceToConnect, char: char, deviceReady: deviceReady)
            }

我希望这可以帮助某人..

**在我的研究中,我发现外设不能作为弱引用传递!

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 2018-09-29
    • 2017-08-10
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 2013-05-14
    相关资源
    最近更新 更多