screenMonkey MonkeyMan
screenMonkey MonkeyMan

Reputation: 423

How can I get CoreBluetooth delegates to work after moving them to a separate class?

I have created a small project to test Bluetooth using CoreBluetooth framework. In my viewController it works fine like this:

class ViewController: UIViewController {

    var myCentral: CBCentralManager! = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        myCentral = CBCentralManager(delegate: self, queue: nil)

    }
}

extension ViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            central.scanForPeripherals(withServices: nil, options: nil)
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if let name = peripheral.name {
            print(name)
        }
    }
}

However, I would like to move move the Bluetooth stuff to another class and just run it from the viewController. Is that possible? My attempt doesn't work:

In the New class, having moved the Bluetooth stuff:

class BLEhandler: NSObject {
    var centralManager: CBCentralManager!
}

extension BLEhandler: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            central.scanForPeripherals(withServices: nil, options: nil)
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if let name = peripheral.name {
            print(name)
        }
        print(peripheral.name)
    }
}

And calling it from the viewController:

override func viewDidLoad() {
    super.viewDidLoad()
    var centralManager = BLEhandler().centralManager
    centralManager = CBCentralManager(delegate: self, queue: nil)
}

Now it shows nothing but a small log:

[CoreBluetooth] XPC connection invalid

I doubt I can use delegates like this, and I think the solution has something to do with protocols, but I'm not sure. How would you go about moving over delegates to other classes and still get them to work?

Upvotes: 0

Views: 315

Answers (1)

screenMonkey MonkeyMan
screenMonkey MonkeyMan

Reputation: 423

Ok, got it to work by simply declaring it first in ViewController:

var centralManager: BLEhandler!

then in viewDidLoad I initialized it:

centralManager = BLEhandler()

rather than directly initializing it in viewDidLoad.

Upvotes: 1

Related Questions