我刚刚按照本教程Push notification完成了我的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--------
}];
}
它完全适用于本地通知,但对于推送通知,它不起作用。如何实施?需要你的帮助。我需要将通知警报正文放在Label或String。
答案 0 :(得分: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.
}
答案 1 :(得分: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
}
}
答案 2 :(得分:0)
如果您的应用程序在收到远程通知时已在运行,则会调用您的应用程序委托的– application:didReceiveRemoteNotification:
方法;如果应用程序当前未运行并且是为响应通知而启动的,则远程通知信息将被放入– application:didFinishLaunchingWithOptions:
方法的launchOptions
字典中。
答案 3 :(得分: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);
}
}