How to convert value of Type 'CBManagerState' to expected type 'CBCentralManagerState' after conversion to Swift 3.0 syntax?

*爱你&永不变心* 提交于 2019-12-10 11:36:50

问题


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



来源:https://stackoverflow.com/questions/39577272/how-to-convert-value-of-type-cbmanagerstate-to-expected-type-cbcentralmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!