最近在開發(fā)BLE交互的App時,往往出現(xiàn)這樣的場景硫朦,設(shè)備狀態(tài)發(fā)生改變,App可能處于后臺模式背镇,這個時候就要通過本地通知將狀態(tài)提示給用戶咬展。場景的處理過程如下。
1.設(shè)置后臺數(shù)據(jù)交互
首先芽世,我們需要使App能夠在后臺接受到數(shù)據(jù)挚赊,在項(xiàng)目的info.plist
文件中,新建一行Required background modes
济瓢,然后在這一行下加入App shares data using CoreBluetooth
和App communicates using CoreBluetooth
兩項(xiàng)荠割。
2.注冊本地通知
通知的注冊應(yīng)該寫在AppDelegate
中,為了方便管理旺矾,可以寫一個AppDelegate
的分類蔑鹦。
在iOS10之后,蘋果將通知相關(guān)的API統(tǒng)一箕宙,我們應(yīng)該使用UserNotifications.framework
來集中管理和使用 iOS 系統(tǒng)中的通知功能嚎朽。
所以首先我們要#import <UserNotifications/UserNotifications.h>
。
然后注冊通知的相關(guān)代碼如下:
//注冊通知
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 開放了可以直接獲取用戶的通知設(shè)定信息的API哟忍。
[localNotiCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
NSLog(@"%@",settings);
}];
3.創(chuàng)建本地推送
在接受到設(shè)備發(fā)來的數(shù)據(jù)后,我們要創(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);
}];
}
以上锅很,基本完成了從接受數(shù)據(jù)到本地通知的處理。
4.備注
在
AppDelegate
的- (void)applicationWillEnterForeground:(UIApplication *)application
和- (void)applicationWillEnterForeground:(UIApplication *)application
方法中添加[application setApplicationIconBadgeNumber:0];
將通知產(chǎn)生的App圖標(biāo)上的標(biāo)記去掉凤跑。iOS中通知的詳細(xì)剖析文章爆安,請參見活久見的重構(gòu) - iOS 10 UserNotifications 框架解析。