Swift: [CoreBluetooth] 取消弹出控制器后XPC连接无效

3

我有两个视图控制器(ViewController和SecondViewController)。

SecondViewController是一个以弹出窗口形式显示的tableView。该tableView将列出所有发现的BLE设备,当用户点击单元格时,它将连接到所选设备。

一切都正常工作,直到用户解除弹出窗口,当弹出窗口关闭时,下面的错误会立即被打印出来:[CoreBluetooth] XPC connection invalid

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

以下是我的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!)

以下是我在视图控制器中的代码:

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 在 dismiss 后是否被正确释放?我认为 delegate 应该是一个 weak 属性。 - vpoltave
@vpoltave 不,它没有被取消初始化。谢谢您的评论,您有任何关于如何从弹出窗口传递外设和特征的想法吗? - jingling-bell
你能展示一下在哪里给 var delegate: PassDataDelegate? 属性赋值吗? - vpoltave
1个回答

0
我的解决方案相当简单。我只需将我的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)
            }

希望这能帮助到某人。

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


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