用户点击UILocalNotification:它可以将数据传递给应用程序吗?

Jas*_*son 5 iphone ios uilocalnotification

我正在创建一个本地UILocalNotification并将其作为横幅显示给用户.是否可以进行设置,以便当用户点击它并返回应用程序时,应用程序将收到某种特定类型的通知数据?我想在应用程序中打开一个特定的视图控制器.我认为最好的方法是基本上向应用程序发送一个URL,或者是否有办法访问,UILocalNotification以便我可以测试哪种类型并采取正确的行动?

Jas*_*son 6

要从传递给iOS应用程序的本地NSUserNotification获取数据,您需要做的就是实现以下方法:- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification.

问题是,当应用程序处于后台时(即当用户点击通知然后返回到应用程序时)发布本地通知时,以及当时应用程序处于前台时,都会调用此方法.当本地通知触发时(毕竟它是在计时器上).那么当应用程序处于后台或前台时,应该如何判断通知是否被触发?这很简单.这是我的代码:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateInactive) {
        // Application was in the background when notification was delivered.
    } else {
        // App was running in the foreground. Perhaps 
        // show a UIAlertView to ask them what they want to do?
    }
}
Run Code Online (Sandbox Code Playgroud)

此时,您可以处理基于的通知notification.userInfo,该通知包含NSDictionary.


The*_*her 1

我们需要实现 NSUserNotificationCenterDelegate 并定义这个方法:

- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
Run Code Online (Sandbox Code Playgroud)

例子:

这就是我在“通知程序”应用程序中所做的。

- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
NSRunAlertPanel([notification title], [notification informativeText], @"Ok", nil, nil);
}

- (void) userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
notifications=nil;
[tableView reloadData];
[center removeDeliveredNotification: notification];
}
Run Code Online (Sandbox Code Playgroud)

当通知被激活(用户点击)时,我只是通过面板通知用户(我可以使用平视显示器窗口)。在这种情况下,我立即删除发送的通知,但这不是通常发生的情况。通知可以保留有一段时间并在 1/2 小时后删除(这取决于您正在开发的应用程序)。