3

我正在开发一个带有推送通知的简单应用程序,并且我成功地实现了它。当我退出应用程序时,我收到推送通知(运行良好)但是当我打开应用程序并尝试从我的服务器(Web 应用程序)发送消息时,它不会显示任何弹出消息或通知。我错过了什么吗?这是我在 AppDelegate.m 上的代码片段

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {

// Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
 (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
 return YES;
 }


 (void)application:(UIApplication*)application didReceiveRemoteNotification: (NSDictionary*)userInfo{
  NSLog(@"Received notification: %@", userInfo);
  NSString *messageAlert = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
  NSLog(@"Received Push Badge: %@", messageAlert );
  [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:messageAlert];

 }

请帮助我解决这个问题。谢谢。

4

3 回答 3

5

当您的应用程序处于活动模式时,您需要将此方法类似于以下内容放入您的 Appdelegate 类中:-

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {    
    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {
        NSString *cancelTitle = @"Close";
        NSString *showTitle = @"Show";
        NSString *message = [[userInfo valueForKey:@"aps"] valueForKey:@"alert"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"My App Name"
                                                            message:message 
                                                           delegate:self 
                                                  cancelButtonTitle:cancelTitle 
                                                  otherButtonTitles:showTitle, nil];
        [alertView show];
        [alertView release];


    } else {
        //Do stuff that you would do if the application was not active
    }
}   

还放didFailToRegisterForRemoteNotificationsWithError委托检查失败原因

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 NSString *str = [NSString stringWithFormat: @"Error: %@", error];
    NSLog(@"%@", str);
} 
于 2013-08-06T09:05:35.393 回答
0

你对这段代码有什么期望:[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:messageAlert];??

我猜你错过了一些基础知识.. 要呈现警报,你应该看看UIAlertView. NSNotificationCenter用于应用程序中的内部数据流。(观察者模式)

当您的应用程序运行时,不会自动显示任何警报。您需要从application:didReceiveRemoteNotification:. NSNotificationCenterPush Notifications是完全不同的东西。它们不是彼此的一部分。

于 2013-08-06T08:59:52.327 回答
0

如果我没记错的话,Apple 会在您的应用程序运行与否时将推送通知发送到不同的地方。您只实现了未启动的代码,但没有实现执行期间的部分。

于 2013-08-06T08:59:54.333 回答