由于iOS 9及以下版本,前臺(tái)收到通知時(shí)無法顯示在通知欄的。iOS 10 已經(jīng)開放了前臺(tái)展示通知欄的API。
首先我們來看看低版本的如何處理:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
首先來比較這兩個(gè)API的異同,雖然前者已經(jīng)被蘋果拋棄了,但是在低版本系統(tǒng)我們還是要適配的,最主要的區(qū)別是前者只能在應(yīng)用跑在前臺(tái)時(shí)才能收到,后者則前后臺(tái)都可以收到,而且如果設(shè)置了后臺(tái)模式為Remote Notifications的話,還可以執(zhí)行30s來獲取數(shù)據(jù)。
假如兩者都在Appdelegate里面都實(shí)現(xiàn)的話,系統(tǒng)只會(huì)調(diào)用帶completionHandler的后者。
為了前后臺(tái)通知處理一致,我們實(shí)現(xiàn)后者,大致如下:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
//如果是前臺(tái),使用第三方EBForeNotification定制通知欄界面,假如在后臺(tái)或者未運(yùn)行,則本來就有
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
[EBForeNotification handleRemoteNotification:userInfo soundID:0 isIos10:NO];
}
completionHandler(UIBackgroundFetchResultNoData);
}
下面處理iOS 10的情況:
//new API 設(shè)置前臺(tái)收到遠(yuǎn)程消息時(shí)是否顯示
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
completionHandler(UNNotificationPresentationOptionAlert);
}
//用戶點(diǎn)擊通知欄,前后臺(tái)處理方式一致,需要注意的是以前的低版本的API是收到通知就回調(diào),iOS 10以后則是用戶點(diǎn)擊才回調(diào)
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
//do something
}