如何在后台处理 NSLocal 通知?

how to handle NSLocal Notification in background?

AppDelegate.mclass.

中使用以下方法
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

    if (application.applicationState == UIApplicationStateInactive )
    {
        NSLog(@"app not running");
    }
    else if(application.applicationState == UIApplicationStateActive )
    {
        NSLog(@"App is running");

    }else if(application.applicationState == UIApplicationStateBackground){
        NSLog(@"App is running in background");
    }
}

可能这对您在后台处理本地通知有帮助。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notif{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

    if (application.applicationState == UIApplicationStateInactive )
    {
        NSLog(@"app not running");
    }
    else if(application.applicationState == UIApplicationStateActive )
    {
        NSLog(@"App is running");

    }else if(application.applicationState == UIApplicationStateBackground){
        NSLog(@"App is running in background");
    }
}

除了 JAGAT 对 iOS 8+ 的回答之外,您还需要请求许可才能注册收听本地通知。你可以使用这个:

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler{

}

为了获得许可,请这样做:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                         settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                         categories:nil]];
}