1

我刚刚按照本教程推送通知,我成功地为我的 iPhone 应用程序实现了推送通知。我现在可以获得通知详细信息。但是,我想将通知 alertBody 放在为通知 alertBody 提供的标签上。

我有一个代码可以显示来自本地通知的通知 alertBody。但我知道它与推送通知不同,因为它仅用于本地通知。

在我的 AppDelagate.m

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif {
NSLog(@"Recieved Notification %@",notif);
NSString *_stringFromNotification = notif.alertBody;
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification" object:_stringFromNotification];
}

在我的 ViewController.m

- (void)viewDidLoad{

 [super viewDidLoad];     

[[NSNotificationCenter defaultCenter] addObserverForName:@"Notification" object:nil queue:nil usingBlock:^(NSNotification *note)
NSString *_string = note.object;
//Do something with the string--------
}];

}

它在本地通知上完美运行,但对于推送通知,它不起作用。如何实施?需要你的帮助。我需要将通知警报正文放在标签或字符串中。

4

4 回答 4

3
first of all register for remote notifications in AppDelegate.m in method,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Invoke APNS.
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}

And then use following delegate method to recieve remote notification:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"Received =%@",userInfo);////userInfo will contain all the details of notification like alert body.
}
于 2013-08-06T10:54:24.607 回答
0

远程通知在应用程序运行的沙箱之外运行,因此您无法像本地通知一样捕获通知,即application:didReceiveLocalNotification. 但是,如果应用程序是通过远程通知启动的,您可以通过application:didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];

    if (notification) {
        // do something with the notification.alertBody
    } else {
        // from the springboard
    }
}
于 2013-08-05T19:21:01.967 回答
0

如果您的应用程序在收到远程通知时已经在运行,– application:didReceiveRemoteNotification:则将调用您的应用程序委托的方法;如果应用程序当前未运行并且响应通知而启动,则远程通知信息将被放入您方法中的launchOptions字典中。– application:didFinishLaunchingWithOptions:

于 2013-08-05T19:21:38.937 回答
0

您正在实施的方法仅用于本地通知。如果要处理推送通知,则必须使用方法

- (void)application:(UIApplication*)application didReceiveRemoteNotification: (NSDictionary*)userInfo{
NSLog(@"Received notification: %@", userInfo);

}

对于相同的。如果应用程序仅在后台运行,则将调用此方法。如果应用程序不在后台,那么您可以通过以下方式获取数据

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
UILocalNotification *notificationData = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];

if(!notificationData){
    NSLog(@"App launched by tapping on app icon");
}else{
    NSLog(@"Notification data -> %@",notificationData);
}
}
于 2013-08-05T19:23:18.643 回答