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?
You can simply omit the enumeration type name and just use the .value. This will compile without warnings and works on iOS 10 and earlier since the underlying raw values are compatible.
I worked around this issue on Xcode 8 with Swift 2.3 (targeting iOS 8 and above) by creating an extension property on
CBCentralManager
which is of the old enum type,CBCentralManagerState
. I named itcentralManagerState
. I refer toCBCentralManager.centralManagerState
where I used to refer toCBCentralManager.state
.I got the idea from this forum thread though they hadn't posted the code yet.
func centralManagerDidUpdateState(central: CBCentralManager) {
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: