shi*_*him 0 iphone notifications bluetooth objective-c ios
当我的iOS应用程序打开时,它会显示本地蓝牙设备列表,然后单击一个.如果蓝牙已关闭,则会出现一个系统警报,要求您打开它(使用按钮转到"设置",另一个按钮单击"确定"); 如果您打开设置,它不会再次扫描,您必须
如何在蓝牙打开时注册一种运行方法的通知?
我看到了一些关于"BluetoothAvailabilityChangedNotification"的内容,但是当打开/关闭蓝牙时似乎没有调用它.
这是我试过的代码:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(bluetoothAvailabilityChanged:)
name:@"BluetoothAvailabilityChangedNotification"
object:nil];
Run Code Online (Sandbox Code Playgroud)
...
-(void) bluetoothAvailabilityChanged: (NSNotification*) notification {
NSLog(@"Bluetooth changed %@",notification.description);
}
Run Code Online (Sandbox Code Playgroud)
为了获得蓝牙状态更改指示,您可以尝试使用CoreBluetooth lib
1.将CoreBluetooth.framework链接到您的项目
2. #import <CoreBluetooth/CoreBluetooth.h>在您的.h文件中
3.实现CBCentralManagerDelegate
4.使用self作为委托初始化管理器
CBCentralManager *centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
5.将其作为属性保存为只要您需要更新:
self.centralManager = centralManager;
6.实现此方法:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if ([central state] == CBCentralManagerStatePoweredOff) {
NSLog(@"Bluetooth off");
}
else if ([central state] == CBCentralManagerStatePoweredOn) {
NSLog(@"Bluetooth on");
}
}
Run Code Online (Sandbox Code Playgroud)
现在尝试启用/禁用蓝牙并查看控制台以获取日志