iOS BLE的后臺數據接收和本地通知處理

最近在開發(fā)BLE交互的App時,往往出現這樣的場景,設備狀態(tài)發(fā)生改變,App可能處于后臺模式,這個時候就要通過本地通知將狀態(tài)提示給用戶。場景的處理過程如下。

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.創(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 框架解析

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 概述 在多數移動應用中任何時候都只能有一個應用程序處于活躍狀態(tài),如果其他應用此刻發(fā)生了一些用戶感興趣的那么通過通知...
    莫離_焱閱讀 6,713評論 1 8
  • 極光推送: 1.JPush當前版本是1.8.2,其SDK的開發(fā)除了正常的功能完善和擴展外也緊隨蘋果官方的步伐,SD...
    Isspace閱讀 6,875評論 10 16
  • -Begin to cook- 黑芝麻餅干 用料 蛋白 2個 細砂糖 15克 低筋面粉 30克 玉米油 40克 黑...
    河州生活圈閱讀 602評論 0 0
  • 薔薇開放 成就著古老的墻 精致美雅的花兒 是謹慎的內斂 少婦折下一朵 別上微卷的長發(fā) 年長的女人愛上沉默 把它們 ...
    忘記結冰閱讀 126評論 1 3
  • 陳宗杰 山東恒泰紡織有限公司 六項精進第203期學員 日精進打卡第2日 【知~學習】努力學習,使自己成長 讀《...
    C人在旅途閱讀 182評論 0 0

友情鏈接更多精彩內容