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