检测用户是否打开或关闭了 Wifi 或蓝牙 [英] Detecting if Wifi or Bluetooth is turned on or off by the user
问题描述
我们如何使用 Swift 语言确定蓝牙或 Wifi 是否已打开/关闭?
How can we determine if Bluetooth or Wifi was turned on/off using the Swift language?
我的应用程序使用蓝牙或 Wifi 与其他设备通信.我们对这些通信没有问题,但我们想通知用户 Wifi 和/或蓝牙是否关闭(当用户使用应用程序时).我无法在 Swift 中做到这一点.
My application uses Bluetooth or Wifi to communicate with other devices. We have no problem with these communications, but we would like to inform the user if Wifi and/or Bluetooth is turned off (when the user is using the application). I haven't been able to do this in Swift.
推荐答案
对于 iOS 中的蓝牙,您有 CBPeripheralManager(在 CoreBluetooth 框架中).要检查蓝牙连接,您将类声明为 CBPeripheralManager 的委托,然后创建一个局部变量:
For Bluetooth in iOS, you have CBPeripheralManager (in CoreBluetooth Framework). To check for bluetooth connection, you declare your class as delegate of CBPeripheralManager then create a local variable:
var myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
然后,您的类必须实现回调,以便在启用或禁用蓝牙时引起注意.下面的代码是从我的项目中提取的,用于 Beacon manager
then, your class must implement the callback to get noticed when your Bluetooth is enabled or disabled. The code below is extracted from my project which is for Beacon manager
//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
And for Wifi, take a look at this Github: https://github.com/ashleymills/Reachability.swift
这篇关于检测用户是否打开或关闭了 Wifi 或蓝牙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!