应用程序处于活动状态时iphone本地通知

时间:2012-04-24 05:40:09

标签: iphone notifications

我正在为iOS开发聊天应用程序5.我遇到了本地通知问题。 当应用程序进入后台状态时,我使用此代码:

  UILocalNotification *localNotification = [[UILocalNotification alloc] init];
  localNotification.alertAction = @"Ok";
  localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n%@",message.sender,message.message];

  [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
  [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
  [localNotification release];

但是当应用程序处于活动状态时,它不在聊天页面中,那么我也需要本地通知,但我也使用相同的代码 通知是在托盘中,但横幅不会来...... ....

请帮帮我......

2 个答案:

答案 0 :(得分:1)

将以下方法放入您的应用程序委托

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
{
    UILocalNotification *localNotif =notification;
    NSString *strBody=[localNotif.userInfo valueForKey:@"Body"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Your Application name" 
                                                    message:strBody
                                                   delegate:self cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil];
    [alert show];

    //NSLog(@"Incoming notification in running app");

    // Access the payload content
    //NSLog(@"Notification payload: %@", [notification.userInfo objectForKey:@"body"]);

    application.applicationIconBadgeNumber = 0;
}

答案 1 :(得分:0)

以下代码处理远程和本地通知

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [self showNotificationAlert:notification.alertBody];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSString *alertMsg = nil;
    id alert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];

    if ([alert isKindOfClass:NSString.class])
        alertMsg = alert;
    else if ([alert isKindOfClass:NSDictionary.class])
        alertMsg = [alert objectForKey:@"body"];

    [self showNotificationAlert:alertMsg];
}

- (void)showNotificationAlert:(NSString *)alertMsg
{
    if (!alertMsg)
        return;

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", nil)
                                                    message:alertMsg
                                                   delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil)
                                          otherButtonTitles:nil];
    [alert show];

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}