使用UNUserNotificationCenter后未调用didReceiveLocalNotification

use*_*894 7 cocoa-touch ios uilocalnotification usernotifications

我正在安排本地通知.它适用于iOS 9.x但是从iOS 10开始

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
Run Code Online (Sandbox Code Playgroud)

应用程序在iOS 10上运行时不会调用.

我知道iOS已经引入了新的UserNotifications框架,但不应该停止使用iOS 9 API.

我该如何解决这个问题?

Bal*_*ato 6

如您所知,iOS 10引入了UNUserNotifications框架来处理本地和远程通知.使用此框架,您可以设置委托以检测何时显示或点击通知.

[UNUserNotificationCenter currentNotificationCenter].delegate = yourDelegate;
Run Code Online (Sandbox Code Playgroud)

...

// In your delegate ...

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {

    // Notification arrived while the app was in foreground

    completionHandler(UNNotificationPresentationOptionAlert);
    // This argument will make the notification appear in foreground
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {

    // Notification was tapped.

    completionHandler();
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你仍然希望使用旧的(不推荐)application:didReceiveLocalNotificationapplication:didReceiveRemoteNotification:fetchCompletionHandler,解决方法很简单:只要不设置任何委托UNUserNotificationCenter.

需要注意的是无声的远程通知(那些包含的content-available关键,没有alert,soundbadge)总是被处理application:didReceiveRemoteNotification:fetchCompletionHandler,即使你已经设置委托.