ios - NSNotification(或类似的)来检测 iOS 上蓝牙连接的变化?

标签 ios iphone objective-c bluetooth notifications

当我的 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/

相关文章:

iphone - 为什么在使用全局调度队列时不调用 NSURLConnection 委托(delegate)方法?

ios - 在 iOS 中检测未触摸 3 秒?

iphone - 没有服务器的 iOS 在线游戏?

ios - 由于简单模式 segue 上未捕获的异常 'NSUnknownKeyException' 而终止应用程序

ios - 如何将消息的收件人和正文设置为 NSString 属性?

iphone - 分发定制 iPhone 应用程序的正确方法是什么?

iphone - 删除 Xcode 4 中的图标斜角

objective-c - 为什么 Helvetica Neue Bold 字形不会在 NSBezierPath 中绘制为普通子路径?

objective-c - 如何使PNG变暗?

iphone - View 不是从iOS7状态栏的底部开始