IOS获取蓝牙状态

发布时间 2023-04-05 09:42:35作者: R1cardo

IOS获取蓝牙状态

监听蓝牙状态

Link Binaries With Libraries中添加CoreBluetooto.framework

WX20230405-092153_2x

创建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 {}
    }

直接获取CBCentralManagerstate,和上面监听代码中的state一样