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

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

1.设置后台数据交互

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

info.plist示例图:
infoplist示例.png

2.注册本地通知

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

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

所以首先我们要#import <UserNotifications/UserNotifications.h>

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

   //注册通知
    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 框架解析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知...
    莫离_焱阅读 6,560评论 1 8
  • 极光推送: 1.JPush当前版本是1.8.2,其SDK的开发除了正常的功能完善和扩展外也紧随苹果官方的步伐,SD...
    Isspace阅读 6,792评论 10 16
  • -Begin to cook- 黑芝麻饼干 用料 蛋白 2个 细砂糖 15克 低筋面粉 30克 玉米油 40克 黑...
    河州生活圈阅读 557评论 0 0
  • 蔷薇开放 成就着古老的墙 精致美雅的花儿 是谨慎的内敛 少妇折下一朵 别上微卷的长发 年长的女人爱上沉默 把它们 ...
    忘记结冰阅读 111评论 1 3
  • 陈宗杰 山东恒泰纺织有限公司 六项精进第203期学员 日精进打卡第2日 【知~学习】努力学习,使自己成长 读《...
    C人在旅途阅读 170评论 0 0