Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conform to CBCentralManagerDelegate Protocol?

I am trying to initialize a central manager instance to make an app with Bluetooth connectivity.

This is part of my code:

class ViewController: UIViewController, CBCentralManagerDelegate {
   var myCentralManager = CBCentralManager(delegate: self, queue: nil) //error on this line
   func centralManagerDidUpdateState(central: CBCentralManager!) { 
}

I get an error:

"Type 'ViewController -> () -> ViewController!' does not conform to protocol 'CBCentralManagerDelegate'

The only method required by the protocol is centralManagerDidUpdateState() which I have added, so why do I get an error?

like image 661
Faris Avatar asked Jan 25 '15 06:01

Faris


2 Answers

The error message is a little deceiving and is pointing you away from the actual issue. The problem is that you are accessing self in the initializer for a stored property, which you can't do like this.

One workaround is to simply declare the property without initializing it, and then move the assignment to the variable to somewhere like an initializer for your view controller, or one of your view controller's lifecycle methods, like viewDidLoad.

like image 75
Mick MacCallum Avatar answered Oct 13 '22 04:10

Mick MacCallum


When you create a central manager, the central manager calls centralManagerDidUpdateState method of its delegate object. So you have to implement this delegate method to ensure that Bluetooth low energy is supported and available to use the central device. Like below:

func centralManagerDidUpdateState(central: CBCentralManager!){
    println("CentralManager is initialized")

    switch central.state{
    case CBCentralManagerState.Unauthorized:
        println("The app is not authorized to use Bluetooth low energy.")
    case CBCentralManagerState.PoweredOff:
        println("Bluetooth is currently powered off.")
    case CBCentralManagerState.PoweredOn:
        println("Bluetooth is currently powered on and available to use.")
    default:break
    }
}
like image 34
Chenghao Lv Avatar answered Oct 13 '22 03:10

Chenghao Lv