我正在使用CoreBluetooth创建应用程序,我希望它在后台运行并执行与蓝牙相关的任务。
有人可以解释一下如何在appdelegate中重新实现中央管理器对象吗?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
for (NSString *identifier in centralManagerIdentifiers) {
if ([identifier isEqualToString:@"myCentral"]) {
// what to do here?
}
}
答案 0 :(得分:3)
我假设您想要恢复应用代理中的多个核心,如"Reinstantiate Your Central and Peripheral Managers" section of the documentation中所述?
如果是这样,我可以看到didFinishLaunchingWithOptions看起来像这样:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.referencesToCentrals = [NSMutableArray array];
NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
if ((centralManagerIdentifiers) && (centralManagerIdentifiers.count > 0)) {
// The system knows about one or more centrals that need to be restored.
for (NSString *identifier in centralManagerIdentifiers) {
CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBPeripheralManagerOptionRestoreIdentifierKey : identifier}];
[self.referencesToCentrals addObject:manager];
}
}
else {
// No centrals need to be restored. If desired, create one for use and save a reference like this:
CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBPeripheralManagerOptionRestoreIdentifierKey : [[NSUUID UUID] UUIDString]}];
[self.referencesToCentrals addObject:manager];
}
// Set up window, etc...
return YES;
}
您可能不希望在应用程序委托中保留对所有核心的引用,因为我在此示例中所做的也不一定让您的应用程序委托充当中心的CBCentralManagerDelegate,但您明白了......