iPhone SDK中的前台本地通知

8
当应用程序在前台运行且正在运行时,本地通知会显示在iPhone SDK中吗?
5个回答

9
不,你将在appdelegate中收到通知。
- (void) application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification {
    //Place your code to handle the notification here.
}

非常感谢。现在,我已经在应用程序didReceiveLocalNotification方法中保留了一个UIAlertView,以便在应用程序已经运行时可以使用它来代替通知。但是当应用程序在后台运行并且通知被触发时,当应用程序回到前台时,该方法被调用并且alertView出现。你能告诉我如何避免这种情况吗? - Dip Dhingani
好的,我们有applicationWillEnterForeground方法来处理这个。抱歉,问题有点傻!非常感谢。 - Dip Dhingani
不是愚蠢的问题 - 你刚给了我我想要的答案 :-) - Jonathon Horsman

3
我制作了一个库,能够制作出几乎与本地通知相同的动画。
请参考以下链接: https://github.com/OpenFibers/OTNotification 演示: enter image description here enter image description here 当您收到消息时,您可以向此库发布新消息。
- (void) application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification
{
    OTNotificationManager *notificationManager = [OTNotificationManager defaultManager];
    OTNotificationMessage *notificationMessage = [[OTNotificationMessage alloc] init];
    notificationMessage.title = [self notificationTitle];
    notificationMessage.message = @"A notification. Touch me to hide me.";
    [notificationManager postNotificationMessage:notificationMessage];
}

2
接受的答案是正确的,但仅此还不足以接收所有通知并向用户展示内容。
- (void) application:(UIApplication *)application didReceiveLocalNotification:    (UILocalNotification *)notification {

您需要检查,这是否是当前通知。有时会出现其他通知(例如当您取消它们时)。因此,您需要检查,您期望的是什么:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    if (fabs([[NSDate date] timeIntervalSinceDate:[notification fireDate]]) <= 0.5f)
    {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Notification alert", @"")
                                    message:notification.alertBody
                                   delegate:self
                          cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];    
    }
}

0
如果您的应用程序当前在前台,则以下函数将在您的委托中被调用:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)Notifikation

你可以决定是否显示一个警告框,但标准的警告框不会自动显示出来。


1
无论应用程序是否已经运行,都会调用此函数。 - Jonathon Horsman

0

Swift 2.2:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    var state = application.applicationState
    if state == .Active {
        // handle the notification, e.g. show an alert 
    } 
}

Swift 3.0:

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    var state: UIApplicationState = application.applicationState
    if state == .active {
        // handle the notification, e.g. show an alert
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接