iOS BLE的后台数据接收和本地通知处理

最近在开发BLE交互的App时,往往出现这样的场景,设备状态发生改变,App可能处于后台模式,这个时候就要通过本地通知将状态提示给用户。场景的处理过程如下。

1.设置后台数据交互

首先,我们需要使App能够在后台接受到数据,在项目的info.plist文件中,新建一行Required background modes,然后在这一行下加入App shares data using CoreBluetoothApp communicates using CoreBluetooth两项。

info.plist示例图:
iOS BLE的后台数据接收和本地通知处理_第1张图片
infoplist示例.png

2.注册本地通知

通知的注册应该写在AppDelegate中,为了方便管理,可以写一个AppDelegate的分类。

在iOS10之后,苹果将通知相关的API统一,我们应该使用UserNotifications.framework来集中管理和使用 iOS 系统中的通知功能。

所以首先我们要#import

然后注册通知的相关代码如下:

   //注册通知
    UNUserNotificationCenter *localNotiCenter = [UNUserNotificationCenter currentNotificationCenter];
    localNotiCenter.delegate = self;
    [localNotiCenter requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"request authorization successed!");
        }
    }];
    
    //iOS10之后, apple 开放了可以直接获取用户的通知设定信息的API。
    [localNotiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"%@",settings);
    }];

3.创建本地推送

在接受到设备发来的数据后,我们要创建本地通知。
创建通知的代码如下:

- (void)creatLocalNotificationWithTitle:(NSString *)title WithBody:(NSString *)body {
    UNMutableNotificationContent *notiContent = [[UNMutableNotificationContent alloc] init];
    notiContent.title = title;
    notiContent.body = body;
    notiContent.badge = @1;
    notiContent.sound = [UNNotificationSound defaultSound];
    
    UNTimeIntervalNotificationTrigger *trigger1 = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requertIdentifier content:notiContent trigger:trigger1];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"Error:%@",error);
    }];
}

以上,基本完成了从接受数据到本地通知的处理。

4.备注

  • AppDelegate- (void)applicationWillEnterForeground:(UIApplication *)application- (void)applicationWillEnterForeground:(UIApplication *)application方法中添加[application setApplicationIconBadgeNumber:0];将通知产生的App图标上的标记去掉。

  • iOS中通知的详细剖析文章,请参见活久见的重构 - iOS 10 UserNotifications 框架解析。

你可能感兴趣的:(iOS BLE的后台数据接收和本地通知处理)