How to convert value of Type 'CBManagerState&#

2019-06-07 04:04发布

问题:

I am working on an iOS App which uses the CoreBluetooth Central Manager. The app was working as expected, until I updated to xCode 8. This update somehow forced me to convert the code from Swift 2.3 to Swift 3.0 with the conversion manager. After this, I got the error message 'cannot convert value of Type 'CBManagerState' to expected argument type 'CBCentralManagerState' and I was searching for an answer, but due to the reason the update is new, there aren't any helpful issues or documentation regarding the CB Bluetooth used with Swift 3.0 or iOS 10.0.

The lines marked with a star are the lines which produced the error.

final class BluetoothSerial: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    ....//some code here from HM10 Bluetooth Serial
    var centralManager: CBCentralManager! 
    var state: CBCentralManagerState { get { return centralManager.state } *

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
      //note that "didDisconnectPeripheral" won't be called if BLE is turned off while connected

       connectedPeripheral = nil
       pendingPeripheral = nil

       //send it to the delegate
       delegate.serialDidChangeState(central.state) *
   }
 }

Any help is appreciated. Thanks in advance.

回答1:

This compiles for me:

var state: CBCentralManagerState { get { return CBCentralManagerState(rawValue: centralManager.state.rawValue)! }

According to the dev forums:

The enums are binary compatible so your code will run fine on any iOS version

I'm only using the state in the centralManagerDidUpdateState func - but doing so as follows:

switch central.state{
    case .poweredOn:
        NSLog("CoreBluetooth BLE hardware is powered on");
        break
    case .poweredOff:
        NSLog("CoreBluetooth BLE hardware is powered off");
        break;
    case .unauthorized:
        NSLog("CoreBluetooth BLE state is unauthorized");
        break
    case .unknown:
        NSLog("CoreBluetooth BLE state is unknown");
        break;
    case .unsupported:
        NSLog("CoreBluetooth BLE hardware is unsupported on this platform");
        break;
    default:
        break
    }

Which the compiler seems to be happy with (ie - removing the preceding CBCentralManager from CBCentralManager.poweredOn