Search code examples
swiftviewcontrollercore-bluetoothdelegationcbcentralmanager

CoreBluetooth set central delegate to another view controller


I have just started translating my app to Swift, I want the CBCentralManager.delegate to be set to another view controller(One that navigation controller pushes onto).

I am trying to do the same with following code:

let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView")
self.navigationController?.pushViewController(viewCont, animated: true)
manager.delegate = viewCont

The variable manager is an instance of CBCentralManager and setting delegate to viewCont raises following error:

"Cannot assign value of type 'UIViewController' to type 'CBCentralManagerDelegate?'"

The declaration for the view Controller:

class MainViewController: UIViewController, CBCentralManagerDelegate

How can I solve the same?


Solution

  • You need to downcast the view controller you receive from instantiateViewControllerWithIdentifier. Without the downcast, all the compiler knows is that you have a UIViewController

    let viewCont = self.storyboard!.instantiateViewControllerWithIdentifier("mainView") as! MainViewController
    self.navigationController?.pushViewController(viewCont, animated: true)
    manager.delegate = viewCont
    

    Once you have the downcast using as! then the compiler knows that it has a MainViewController and since this class is also a CBCentralManagerDelegate it is happy.