首页 > 解决方案 > 多人连接 wifi 和蓝牙关闭

问题描述

iOS中有什么方法可以检测Wifi和蓝牙是否关闭,以便我可以向用户显示警报以从设置中启用它。

注意:我感兴趣的是硬件设置是开/关,而不是互联网是否可以访问。

标签: iosobjective-cswiftxcodemultipeer-connectivity

解决方案


//对于 Wifi 使用 SwiftReachability https://github.com/ashleymills/Reachability.swift

//声明这个属性不会超出你的监听器的范围

 let reachability = try! Reachability()

//declare this inside of viewWillAppear

     NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
      try reachability.startNotifier()
    }catch{
      print("could not start reachability notifier")
    }

  @objc func reachabilityChanged(note: Notification) {
   let reachability = note.object as! Reachability
     switch reachability.connection {
  case .wifi:
      print("Reachable via WiFi")
  case .cellular:
      print("Reachable via Cellular")
  case .unavailable:
    print("Network not reachable")
  }
}

停止通知

reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)

// 蓝牙导入 CoreBluetooth

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

//BT管理器

func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager)
{

    if peripheral.state == .poweredOn {
   // myBTManager!.startAdvertising(_broadcastBeaconDict)
    } else if peripheral.state == .poweredOff {
   // myBTManager!.stopAdvertising()
    } else if peripheral.state == .unsupported
    {
    } else if peripheral.state == .unauthorized
      {
      }
 }

推荐阅读