swift - 检测用户是否打开或关闭 Wifi 或蓝牙

标签 swift bluetooth wifi

<分区>

我们如何使用 Swift 语言确定蓝牙或 Wifi 是否打开/关闭?

我的应用程序使用蓝牙或 Wifi 与其他设备通信。我们对这些通信没有问题,但如果 Wifi 和/或蓝牙关闭(当用户正在使用应用程序时),我们想通知用户。我无法在 Swift 中做到这一点。

最佳答案

对于 iOS 中的蓝牙,您有 CBPeripheralManager(在 CoreBluetooth 框架中)。要检查蓝牙连接,您将您的类声明为 CBPeripheralManager 的委托(delegate),然后创建一个局部变量:

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

然后,您的类必须实现回调以在启用或禁用蓝牙时得到通知。下面的代码是从我的 Beacon 管理器项目中提取的

//BT Manager
    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
        println(__FUNCTION__)
        if peripheral.state == CBPeripheralManagerState.PoweredOn {
            println("Broadcasting...")
            //start broadcasting
            myBTManager!.startAdvertising(_broadcastBeaconDict)
        } else if peripheral.state == CBPeripheralManagerState.PoweredOff {
            println("Stopped")
            myBTManager!.stopAdvertising()
        } else if peripheral.state == CBPeripheralManagerState.Unsupported {
            println("Unsupported")
        } else if peripheral.state == CBPeripheralManagerState.Unauthorized {
            println("This option is not allowed by your application")
        }
     }

对于 Wifi,看看这个 Github:https://github.com/ashleymills/Reachability.swift

关于swift - 检测用户是否打开或关闭 Wifi 或蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075198/

相关文章:

android - getbondeddevices() 不返回配对的蓝牙设备

java - Android 蓝牙 - 无法连接

ios - UINavigationBar.appearance().translucent 正在创建一个大的空白

ios - 从 Swift 中的相机胶卷连拍中删除单张照片

ios - 需要使用展开/折叠功能按字母顺序对 UITableView 进行分组

swift - 使用Alamofire将图像上传到服务器

iOS - iOS 设备和外部附件(蓝牙 watch )之间 BLE 数据传输的 MTU 大小

Android:在应用程序中间从 3G 切换到 WIFI = 网络连接丢失

ios - 即使应用程序未运行,网络扩展也可监控 WiFi 网络变化

android - android系统多久扫描一次wifi