【发布时间】:2014-11-22 04:49:18
【问题描述】:
我从事这个项目已经有一段时间了。当应用在后台的应用切换器中时,需要定期从蓝牙设备收集数据。
我最近的想法是在蓝牙设备连接时使用 Core Bluetooth 通知我的应用,这样我就可以检查它是否是我的设备,然后做我需要做的事情。
或者当它说:“didConnectPeripheral”时我错过了解释文档?
我无法在我的 CBCentralManager 对象中找到函数来启动某种“观察者”来给我这些通知。
我是不是走错路了?
谢谢。
代码尝试使用核心蓝牙:
CBCentralManager *mgr;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
mgr = [CBCentralManager alloc];
CBPeripheral *peripheral = [CBPeripheral alloc];
[mgr connectPeripheral:peripheral options:nil];
// Override point for customization after application launch.
return YES;
}
- (void) mgr:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
NSLog(@"Device Connected!");
}
- (void) mgr:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@"Device Disconnected!");
}
- (void)mgr:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(@"Did discover peripheral. peripheral: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.UUID, advertisementData);
//Do something when a peripheral is discovered.
}
得到错误:
2014-11-21 23:30:27.730 TelematicsService[436:185202] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(0x286db49f 0x35e91c8b 0x285fb873 0x285fb657 0x283adb85 0xf005f 0x2bc084f1 0x2bdfd43f 0x2bdff98b 0x2be0a209 0x2bdfe217 0x2ee6c0d1 0x286a1d7d 0x286a1041 0x2869fb7b 0x285ed3c1 0x285ed1d3 0x2bc021bf 0x2bbfcfa1 0xf2a29 0x36411aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
我相信由于外围设备没有完全定义
【问题讨论】:
-
只需向您的外围设备发出
connect。当外围设备在didConnectPeripheral范围内时,即使您的应用程序在后台,也会被调用。如果您希望它在应用程序/设备重启时工作,请在 Core Bluetooth 编程指南中查找状态恢复 -
有趣,我使用的是硬件制造商提供的库,负责处理设备的所有蓝牙和通信协议。你说的connect是指对象CBCentralManager的connectPeripheral吗?
-
是的。核心蓝牙编程指南讨论后台连接 - developer.apple.com/library/ios/documentation/…
-
任何供应商库都应该在内部使用相同的调用,所以它应该工作相同
-
是否可以将 CBPeripheral 定义为具有特定通信协议的任何设备?编辑:查看他们使用 ExternalAccessory.h 的代码 Edit2:另一个注意事项是他们的库不是用英文编写的,所以要弄清楚发生了什么并不容易。(但 lib 有效)
标签: ios core-bluetooth