如何在iOS中查找背景中的蓝牙设备时显示本地通知?

时间:2017-02-14 23:50:52

标签: ios iphone bluetooth background-process core-bluetooth

我有一个iOS(Objective-c)应用程序,我连接了一个钥匙链蓝牙。然后我连接这个,我想按我的iPhone的主页按钮(所以应用程序转到后台)然后,当CoreBluetooth再次检测到钥匙串时发送UILocalNotification。

我已经阅读了这篇文章的任何帖子,并且是可能的,因为它来自后台并且它可以做到。但是我无法显示此通知,因为没有扫描然后按主页按钮并存在像willRestoreState这样的功能给我们Apple ...

这是我的代码:

#import "AppDelegate.h"

@import CoreBluetooth;
@interface AppDelegate () <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (readwrite, nonatomic, strong) CBCentralManager *centralManager;
@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.centralManager.delegate = self;
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionRestoreIdentifierKey:@"BF8D9479-FC81-40EE-A9A7-A9AC78E2707D"}];
    //Used to debug CM restore only
    NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
    NSString *str = [NSString stringWithFormat: @"%@ %lu", @"Manager Restores: ", (unsigned long)centralManagerIdentifiers.count];
    NSLog(@"finish");
    [self sendNotification:str];
    for(int i = 0;i<centralManagerIdentifiers.count;i++)
    {
        [self sendNotification:(NSString *)[centralManagerIdentifiers objectAtIndex:i]];
    }

    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
    return YES;
}

- (void)centralManager:(CBCentralManager *)central willRestoreState:(NSDictionary *)state {
    //NSArray *peripherals = state[CBCentralManagerRestoredStatePeripheralsKey];

    CBPeripheral *activePeripheral = [state[CBCentralManagerRestoredStatePeripheralsKey] firstItem];
    activePeripheral.delegate = self;
    NSLog(@"willRestore");
    NSString *str = [NSString stringWithFormat: @"%@ %@", @"Device: ", activePeripheral.identifier.UUIDString];
    [self sendNotification:str];
}

-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    NSLog(@"centralManagerDidUpdateState called");
    if (central.state != CBCentralManagerStatePoweredOn) {
        // error handling
    }
    else {
        NSLog(@"scanning for peripherals");
        //following call will result in callback to centralManager didDiscoverPeripheral ...
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
        [central scanForPeripheralsWithServices:@[@"BF8D9479-FC81-40EE-A9A7-A9AC78E2707D"] options:options];
    }
}

//sendNotification is a func that creates a local notification for debugging when device connected to comp
-(void)sendNotification: (NSString *)string{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:1];
    notification.alertBody = @"Hi! Slide to open the app :)";
    notification.soundName =  @"Alarm-Clock.caf";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"Back back");

}

    - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    CBPeripheral* currentPer = peripheral;
    NSLog(@"Discorvery");
    if(![cbArray containsObject:currentPer])
    {
        [cbArray addObject:currentPer];

        if([currentPer.name containsString:@"blue"]){
            NSLog(@"CurrentPer Nombre: %@", currentPer.name);
            NSLog(@"CurrentPer UDID: %@", currentPer.identifier.UUIDString);
            [self.centralManager connectPeripheral:currentPer options:nil];
            [self sendNotification:@"awdwad"];
        }
    }

}

我做错了什么?

编辑:钥匙串与CoreBluetooth完全兼容,是一款智能钥匙链防丢4.0,它有一个按钮。 我已经在我的.plist中添加了背景模式和蓝牙使用的密钥。

0 个答案:

没有答案