5

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

4

3 回答 3

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?
    }
}

此时您可以处理基于notification.userInfoNSDictionary 的通知。

于 2012-11-25T19:25:12.830 回答
1

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

- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification

例子:

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

- (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];
}

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

于 2012-11-23T15:27:45.600 回答
0

1 - 在你的项目中定义一些类来实现 NSUserNoficationCenterDelegate 协议(记录在这里

@interface someObject : NSObject  <NSUserNotificationCenterDelegate>
{ 
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;
}

2 - 将定义为#1 的对象的实例设置为默认通知中心的代表。

[[NSUserNotificationCenter defaultNotificationCenter] setDelegate: someObject];

现在,只要用户点击/单击通知,您就会被调用 didActivateNotification。您将拥有您创建的原始通知。因此,您需要的任何信息都应该可供您使用。

如果您想要/需要特殊信息(通知标题、消息等除外),您可能需要在安排发送通知之前在通知中设置其他应用程序特定信息。例如:

NSUserNotification* notification = [[NSUserNotification alloc] init];
NSDictionary* specialInformation = [NSDictionary dictionaryWithObjectsAndKeys: @"specialValue", @"specialKey", nil];
[notification setUserInfo:specialInformation];
于 2012-12-03T20:11:10.857 回答