使用UNUserNotificationCenter后未调用didReceiveLocalNotification

时间:2016-09-02 21:20:39

标签: ios cocoa-touch uilocalnotification usernotifications

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

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
当应用程序在iOS 10上运行时,

不会被调用。

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

如何解决此问题?

1 个答案:

答案 0 :(得分:4)

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

[UNUserNotificationCenter currentNotificationCenter].delegate = yourDelegate;

...

// 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();
}

现在,如果您仍想使用旧的(已弃用的)application:didReceiveLocalNotificationapplication:didReceiveRemoteNotification:fetchCompletionHandler,解决方案很简单:只需不要将任何代理设置为UNUserNotificationCenter

请注意,静默远程通知(包含content-available密钥而不包含alertsoundbadge的通知)始终由application:didReceiveRemoteNotification:fetchCompletionHandler处理,即使你已经设置了代表。