Reputation: 29
I have 2 ViewController (ViewController & SecondViewController).
The SecondViewController is a tableView that presenting as popover. The tableView will list out all the discovered BLE devices and when the user tap on the cell, it will connect to the selected device.
Everthing works fine until user dismiss the popover, the below error will be printed immediately when popover dismissed. [CoreBluetooth] XPC connection invalid
I am using a protocol delegate to pass the peripheral and characteristic
This is what I have in my 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!)
This is what I have in my ViewController:
extension ViewController: PassDataDelegate {
func passPeripheral(_ device: CBPeripheral!) {
self.device = device
}
func passCharacteristic(_ characteristic: CBCharacteristic!) {
self.characteristic = characteristic
self.deviceReady = true
}
}
In somewhere of my ViewController, I am using deviceReady in a If statement. but it shows that Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value .
Seems like the protocol func is not called?
May I get some help please?
Upvotes: 3
Views: 2031
Reputation: 29
my solution is kinda easy. I just set my ViewController as static then create a setter function for the peripherals properties, then call the setter function in SecondViewController. It works now !!
In 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
}
In SecondViewController:
if let controller = ViewController.vc {
controller.setCB(centralManager: centralManager, deviceToConnect: deviceToConnect, char: char, deviceReady: deviceReady)
}
I hope this can help somebody..
**Throughout my research, I found out that the peripherals can't be passed as a weak reference!!
Upvotes: 0