如何检测用户的iPhone关闭或开启的蓝牙?

问题描述 投票:6回答:2

我试图检测用户的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")
    }
}

但正如你从图中可以看到的那样,出了点问题.enter image description here

你能帮我解决一下这个问题,我是swift和CoreBluetooth技术的新手。我也使用Reachability来检测Wi-Fi连接,所以如果它也适用于蓝牙,我宁愿使用Reachability。

swift bluetooth
2个回答
5
投票
  1. 你应该实现协议CBPeripheralManagerDelegate,所以用CBManager替换你的class定义行中的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) ... }

0
投票

您可以使用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
           }
    }
© www.soinside.com 2019 - 2024. All rights reserved.