【问题标题】:How can I detect is the Bluetooth of the user's iPhone Off or On?如何检测用户 iPhone 的蓝牙是关闭还是打开?
【发布时间】:2016-12-18 12:13:01
【问题描述】:

我正在尝试检测用户 iPhone 的蓝牙是打开还是关闭。如果它关闭,我想向用户发送通知以将其打开。 到目前为止,我已经这样做了:

import CoreBluetooth

  class ViewController: UIViewController, CLLocationManagerDelegate,AVCaptureMetadataOutputObjectsDelegate,CBManager {   

 var myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)

  }

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
    print(#function)
    if peripheral.state == CBManagerState.poweredOn {
        print("Broadcasting...")

    //    myBTManager!.startAdvertising(_broadcastBeaconDict)
    } else if peripheral.state == CBManagerState.poweredOff {
        print("Stopped")
        myBTManager!.stopAdvertising()
    } else if peripheral.state == CBManagerState.unsupported {
        print("Unsupported")
    } else if peripheral.state == CBManagerState.unauthorized {
        print("This option is not allowed by your application")
    }
}

但是从图片中可以看出,有问题。

请您帮我解决这个问题,我是 swift 和 CoreBluetooth 技术的新手。我也在使用 Reachability 来检测 Wi-Fi 连接,所以如果它也适用于蓝牙,那么我更愿意使用 Reachability。

【问题讨论】:

    标签: swift bluetooth


    【解决方案1】:
    1. 您应该正在实现协议CBPeripheralManagerDelegate,因此将class 定义行中的CBManager 替换为CBPeripheralManagerDelegate

    2. 在 Swift 3 中,peripheralManagerDidUpdateState 的签名现在是:

      func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager)
      
    3. 您不能在类创建时初始化CBPeripheralManager,因为self 仅在类初始化后可用。相反,让你的财产:

      var myBTManager: CBPeripheralManager?
      

      并在viewDidLoad中初始化它:

      override func viewDidLoad() {
          ...       
          myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
          ...
      }
      

    【讨论】:

      【解决方案2】:

      您可以使用CBCentralMangerDelegate 方法:

          public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
                  if central.state == .poweredOn {
                      //Bluetooth is on
                 } else if central.state == .poweredOff {
                      //Bluetooth is off
                 }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-17
        • 2016-12-24
        • 2011-09-01
        • 1970-01-01
        • 2011-11-20
        相关资源
        最近更新 更多