Sagar Devkota Sagar Devkota - 2 months ago 42
Swift Question

Xcode 8.0 CBCentralManager Issue

I recently downloaded Xcode 8.0 and trying to run my previous project which uses core bluetooth.

I have enabled Use Legacy Swift Language Version in build setting for compatibility in swift 2.3
everything works, but one Issue occured,

func centralManagerDidUpdateState(central: CBCentralManager)
{
print("state is \(central.state.rawValue)")
if (central.state == CBCentralManagerState.PoweredOn)
{
self.centralManager?.scanForPeripheralsWithServices([serviceUUID], options: nil)
}
else
{
// do something like alert the user that ble is not on
}
}


previously central.state would return CBCentralManagerState type as int but now it returns CBManagerState so got an error so i changed to

if (central.state == CBManagerState.PoweredOn)


But CBManagerState is only supported in IOS 10+ but i want to build it for IOS 8.3+ so how can I change the code?

UPDATE
I also converted project to swift 3.0, but still same issue, so how can i run this project on mobiles with ios version below 10?

Answer

The simplest approach is just to use the short-hand reference to the enumeration value:

func centralManagerDidUpdateState(central: CBCentralManager)
{
    print("state is \(central.state.rawValue)")
    if (central.state == .PoweredOn)
    {
        self.centralManager?.scanForPeripheralsWithServices([serviceUUID], options: nil)
    }
    else
    {
        // do something like alert the user that ble is not on
    }

}

Now your code will compile without errors or warnings and works correctly on all targets

Comments