IOS获取蓝牙状态
监听蓝牙状态
在Link Binaries With Libraries中添加CoreBluetooto.framework
创建CBCentralManager对象
为了避免每次都获取蓝牙状态都弹窗,配置一下options
将CBCentralManagerOptionShowPowerAlertKey
设置为false
let options = [CBCentralManagerOptionShowPowerAlertKey: false]
bluetoothManager = CBCentralManager(delegate: self, queue: nil, options: options)
遵守CBCentralManagerDelegate
,在代理方法centralManagerDidUpdateState
中监听蓝牙改变的状态
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
print("蓝牙开启且可用")
case .unknown:
print("手机没有识别到蓝牙,请检查手机。")
case .resetting:
print("手机蓝牙已断开连接,重置中。")
case .unsupported:
print("手机不支持蓝牙功能,请更换手机。")
case .poweredOff:
print("手机蓝牙功能关闭,请前往设置打开蓝牙及控制中心打开蓝牙。")
case .unauthorized:
print("手机蓝牙功能没有权限,请前往设置。")
PLWToast("无蓝牙权限,请前往设置打开")
default: break
}
isBlueToothOn = central.state != .poweredOff && central.state != .unauthorized && central.state != .unsupported
NotificationCenter.default.post(name: deviceBluetoothNotification, object: isBlueToothOn, userInfo: nil)
}
监听到蓝牙状态改变发送通知,在其他需要用到蓝牙的地方添加NotificationCenter
的Obsever即可
主动获取蓝牙状态
var isBlueToothOn: Bool {
get {
return bluetoothManager?.state != .poweredOff && bluetoothManager?.state != .unauthorized && bluetoothManager?.state != .unsupported
}
set {}
}
直接获取CBCentralManager
的state
,和上面监听代码中的state一样