当应用未运行时,iOS8上的LocalNotification无法正常工作

时间:2015-01-16 23:13:45

标签: ios objective-c ios8 uilocalnotification

我有一个使用本地通知的应用。直到最近一切都运行良好,但在iOS 8发布后,当应用程序未运行(从进程中删除)时,我的本地通知不起作用。这是我在app delegate中设置本地通知的代码。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{      
    [[NSNotificationCenter defaultCenter] postNotificationName:localReceived object:self userInfo:notification.userInfo];

    // Set icon badge number to zero
    application.applicationIconBadgeNumber = 0;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{     
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
    {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:
        UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }
    else if ([UIApplication instancesRespondToSelector:@selector(registerForRemoteNotificationTypes:)])
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }

    ...

    // Local notificaiton example. Icon badge
    UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    NSLog(@"locationNotification:%@",locationNotification.alertBody);
    if (locationNotification) {
        // Set icon badge number to zero
        application.applicationIconBadgeNumber = 0;
        // call local notification method
        [self application:[UIApplication sharedApplication] didReceiveLocalNotification:locationNotification];

    }

    return YES;

}

当我的应用未运行时,会调用didFinishLaunchingWithOptions:方法。在其中我再次调用 didReceiveLocalNotification 方法,我调用 postNotificationName 。我把观察者放在我的ViewControllers ViewDidLoad方法中:

- (void)viewDidLoad
{
    ...
    [[NSNotificationCenter defaultCenter] addObserver:self 
    selector:@selector(recieveLocalNotification:) name:localReceived object:nil];
    ...
}

问题是当app未运行时,永远不会调用 recieveLocalNotification:方法。每次app处于后台或正在运行时都会调用它。任何人都可以告诉我这里我做错了什么吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

在实例化视图控制器视图后调用

-viewDidLoad,在首次访问viewController.view后实例化视图。

因此,您可以在发布通知之前尝试拨打viewController.view