IOS获取蓝牙状态

1|0IOS获取蓝牙状态

1|1监听蓝牙状态

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即可

1|2主动获取蓝牙状态

var isBlueToothOn: Bool { get { return bluetoothManager?.state != .poweredOff && bluetoothManager?.state != .unauthorized && bluetoothManager?.state != .unsupported } set {} }

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


__EOF__

本文作者R1cardo
本文链接https://www.cnblogs.com/r1cardo/p/17288859.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   R1cardo  阅读(487)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示