当我的 iOS 应用程序打开时,它会显示本地蓝牙设备列表,然后您单击一个。如果蓝牙关闭,则会出现系统警报,要求您将其打开(使用一个按钮转到“设置”,另一个按钮单击“确定”);如果您打开设置,它不会再次扫描,您必须
如何注册一种在蓝牙打开时运行方法的通知?
我看到了一些关于“BluetoothAvailabilityChangedNotification”的内容,但是当蓝牙打开/关闭时似乎没有被调用。
这是我试过的代码:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(bluetoothAvailabilityChanged:)
name:@"BluetoothAvailabilityChangedNotification"
object:nil];
...
-(void) bluetoothAvailabilityChanged: (NSNotification*) notification {
NSLog(@"Bluetooth changed %@",notification.description);
}
最佳答案
要获取蓝牙状态变化指示,您可以尝试使用 CoreBluetooth 库
1. 将 CoreBluetooth.framework 链接到您的项目
2. #import <CoreBluetooth/CoreBluetooth.h>
在你的 .h 文件中
3.实现CBCentralManagerDelegate
4. 以自己为代表初始化管理器
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
5. 只要您需要更新,就将其作为属性(property)保留:
self.centralManager = centralManager;
6.实现这个方法:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if ([central state] == CBCentralManagerStatePoweredOff) {
NSLog(@"Bluetooth off");
}
else if ([central state] == CBCentralManagerStatePoweredOn) {
NSLog(@"Bluetooth on");
}
}
现在尝试启用/禁用蓝牙并查看控制台以获取日志
关于ios - NSNotification(或类似的)来检测 iOS 上蓝牙连接的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19597388/