Is there any way in iOS to detect if Wifi & Bluetooth is off so that I can show alert to the user to enable it from settings.
Note: I am interested in the hardware setting is on/off not the internet is reachable or not.
Is there any way in iOS to detect if Wifi & Bluetooth is off so that I can show alert to the user to enable it from settings.
Note: I am interested in the hardware setting is on/off not the internet is reachable or not.
//For Wifi Use SwiftReachability https://github.com/ashleymills/Reachability.swift
//declare this property where it won't go out of scope relative to your listener
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")
}
}
stopping notifications
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
// For bluetooth import CoreBluetooth
var myBTManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
//BT Manager
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
{
}
}
You can try the following for network connection availability
func isInternetAvailable() -> Bool {
var isNetworkReachable = false
if let reachability: Reachability = try? Reachability() {
isNetworkReachable = reachability.connection != .unavailable
}
return isNetworkReachable
}
for BLE
class BLEManager: NSObject, CBCentralManagerDelegate {
var bleManagerDelegate: BLEManagerDelegate?
var bluetoothManager: CBCentralManager?
private override init() {
super.init()
bleManager = CBCentralManager(delegate: self, queue:nil,
options:[CBCentralManagerOptionShowPowerAlertKey: true])
}
//CBCentralManagerDelegate method invoked
func centralManagerDidUpdateState(_ central: CBCentralManager) {
var bleStateError: BLEError = .kBLEStateUnknown
switch central.state {
case .poweredOff:
// powered Off
case .poweredOn:
// powered On
case .unknown:
//
case .resetting:
//
case .unsupported:
//
case .unauthorized:
//
}
}
}