Search code examples
iosswiftios9core-bluetoothios10

CBCentralManager iOS10 and iOS9


So I'm migrating to iOS10 but I also need my code to run on iOS9. I'm using CoreBluetooth and CBCentralManagerDelegate. I can get my code to work for iOS10 however I need the fallback to work for iOS9 as well.

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if #available(iOS 10.0, *) {
        switch central.state{
        case CBManagerState.unauthorized:
            print("This app is not authorised to use Bluetooth low energy")
        case CBManagerState.poweredOff:
            print("Bluetooth is currently powered off.")
        case CBManagerState.poweredOn:
            print("Bluetooth is currently powered on and available to use.")
        default:break
        }
    } else {

        // Fallback on earlier versions
        switch central.state{
        case CBCentralManagerState.unauthorized:
            print("This app is not authorised to use Bluetooth low energy")
        case CBCentralManagerState.poweredOff:
            print("Bluetooth is currently powered off.")
        case CBCentralManagerState.poweredOn:
            print("Bluetooth is currently powered on and available to use.")
        default:break
        }
    }
}

I get the error:

Enum case 'unauthorized' is not a member of type 'CBManagerState'

On the line:

case CBCentralManagerState.unauthorized: 

As well as for .poweredOff and .poweredOn.

Any ideas how I can get it to work in both cases?


Solution

  • I contacted Apple about this and was given the following response (paraphrasing).

    Due to the changing nature of swift, the above implementation is not possible however you can use the rawValue of the enum as the state is identical between the two classes. Therefore the following will work for now:

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if #available(iOS 10.0, *) {
            switch central.state{
            case CBManagerState.unauthorized:
                print("This app is not authorised to use Bluetooth low energy")
            case CBManagerState.poweredOff:
                print("Bluetooth is currently powered off.")
            case CBManagerState.poweredOn:
                print("Bluetooth is currently powered on and available to use.")
            default:break
            }
        } else {
            // Fallback on earlier versions
            switch central.state.rawValue {
            case 3: // CBCentralManagerState.unauthorized :
                print("This app is not authorised to use Bluetooth low energy")
            case 4: // CBCentralManagerState.poweredOff:
                print("Bluetooth is currently powered off.")
            case 5: //CBCentralManagerState.poweredOn:
                print("Bluetooth is currently powered on and available to use.")
            default:break
            }
        }
    }