【问题标题】:Check Bluetooth status - Swift 4检查蓝牙状态 - Swift 4
【发布时间】:2018-04-28 06:40:31
【问题描述】:

我在 Xcode 中遇到了蓝牙问题。我找不到一个很好的解决方案来检查蓝牙是否打开。我只想要那个。我在网上搜索了一些解决方案,但没有什么对我有用。关于如何检查蓝牙的任何想法?我导入了 CoreBluetooth 类并编写了这行代码:

if CBPeripheralManager.authorizationStatus() == .denied { code }
if CBPeripheralManager.authorizationStatus() == .authorized  { code }

【问题讨论】:

    标签: ios swift core-bluetooth


    【解决方案1】:

    为此实现CBCentralManagerDelegate委托。

     var manager:CBCentralManager!
    
     viewDidLoad() {      // Or init()
         manager          = CBCentralManager()
         manager.delegate = self
     }
    

    委托方法:

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            break
        case .poweredOff:
            print("Bluetooth is Off.")
            break
        case .resetting:
            break
        case .unauthorized:
            break
        case .unsupported:
            break
        case .unknown:
            break
        default:
            break
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要使用 CBCentralManager,它提供了委托方法 "centralManagerDidUpdateState" https://developer.apple.com/documentation/corebluetooth/cbcentralmanager

      func centralManagerDidUpdateState(_ central: CBCentralManager)
      {
          if central.state == .poweredOn
          {
              print("Searching for BLE Devices")
      
              // Scan for peripherals if BLE is turned on
          }
          else
          {
              // Can have different conditions for all states if needed - print generic message for now, i.e. Bluetooth isn't On
              print("Bluetooth switched off or not initialized")
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-02
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-19
        相关资源
        最近更新 更多