【发布时间】:2014-09-14 23:22:16
【问题描述】:
我只是想检测,当我的应用在 iPad 上启动时,设备上的蓝牙是否已启用。
具体来说,我想在我的 iPad 上启动应用程序,让应用程序检查是否在后台启用了设备上的蓝牙,如果是,应用程序什么也不做,但如果蓝牙被禁用,它会触发提示用户打开蓝牙的警报。我已经对此进行了研究,但无法为我的问题找到清晰简洁的答案。任何帮助将不胜感激。
【问题讨论】:
标签: ios objective-c ipad ios7 bluetooth
我只是想检测,当我的应用在 iPad 上启动时,设备上的蓝牙是否已启用。
具体来说,我想在我的 iPad 上启动应用程序,让应用程序检查是否在后台启用了设备上的蓝牙,如果是,应用程序什么也不做,但如果蓝牙被禁用,它会触发提示用户打开蓝牙的警报。我已经对此进行了研究,但无法为我的问题找到清晰简洁的答案。任何帮助将不胜感激。
【问题讨论】:
标签: ios objective-c ipad ios7 bluetooth
如果您在应用中实例化 CBCentralManager,ios 会自动提示用户从设置页面启用蓝牙。
在您的 viewDidLoad 或一些顶级函数中添加以下内容:
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
您可以覆盖 'centralManagerDidUpdateState' 来捕获回调:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBCentralManagerStatePoweredOn) {
//Do what you intend to do
} else if(central.state == CBCentralManagerStatePoweredOff) {
//Bluetooth is disabled. ios pops-up an alert automatically
}
}
【讨论】:
iOS 10 接受的答案需要稍微更新。
CBCentralManagerStatePoweredOn 和 CBCentralManagerStatePoweredOff 已被弃用,应替换为 CBManagerStatePoweredOn 和 CBManagerStatePoweredOff。
更新代码:
- (void)centralManagerDidUpdateState:(CBCentralManager*)aManager
{
if( aManager.state == CBManagerStatePoweredOn )
{
//Do what you intend to do
}
else if( aManager.state == CBManagerStatePoweredOff )
{
//Bluetooth is disabled. ios pops-up an alert automatically
}
}
【讨论】: