最近在開發(fā)BLE交互的App時,往往出現這樣的場景,設備狀態(tài)發(fā)生改變,App可能處于后臺模式,這個時候就要通過本地通知將狀態(tài)提示給用戶。場景的處理過程如下。
1.設置后臺數據交互
首先,我們需要使App能夠在后臺接受到數據,在項目的info.plist文件中,新建一行Required background modes,然后在這一行下加入App shares data using CoreBluetooth和App communicates using CoreBluetooth兩項。

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.創(chuàng)建本地推送
在接受到設備發(fā)來的數據后,我們要創(chuàng)建本地通知。
創(chuàng)建通知的代碼如下:
- (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 框架解析。