presentLocalNotificationNow

presentLocalNotificationNow

presentLocalNotificationNowscheduleLocalNotification有什么区别。

对于以下两个功能,在1秒后显示通知

-(void)showLocalNotification:(NSNotification *)notification {

    NSString *msg = @"test message";

    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    UILocalNotification *_localNotification = [[UILocalNotification alloc]init];

    _localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];

    _localNotification.timeZone = [NSTimeZone defaultTimeZone];

    _localNotification.alertBody = msg;

    _localNotification.soundName = UILocalNotificationDefaultSoundName;

    _localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;

    [[UIApplication sharedApplication] scheduleLocalNotification:_localNotification];

    // or

    //[[UIApplication sharedApplication] presentLocalNotificationNow:_localNotification];
}

最佳答案

如果应用程序在后台运行,则本地通知将不会收到警报或声音,因为它是由应用程序直接接收的。在这种情况下,您需要使用presentLocalNotificationNow呈现通知。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    UIApplicationState applicationState = application.applicationState;
    if (applicationState == UIApplicationStateBackground) {
        [application presentLocalNotificationNow:notification];
    }
}

从Apple文档中:

创建UILocalNotification的实例后,您可以安排
它使用UIApplication类的两种方法之一:
scheduleLocalNotification:或presentLocalNotificationNow:。前者
使用火日来安排交货的方法;后一种方法
不管值是多少,都会立即显示通知
fireDate。您可以通过以下方式取消特定或所有本地通知
调用cancelLocalNotification:或cancelAllLocalNotifications,
分别。

09-11 19:15