2013-08-05 21 views
1

我剛剛按照本教程Push notification,我成功實現了我的iPhone應用程序的推送通知。我能夠得到現在的通知細節。但是,我想將通知alertBody放在提供通知alertBody的標籤上。如何從我的應用程序從遠程推送通知中獲取notification.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-------- 
}]; 

} 

它完美對本地通知,但對於推送通知,它不工作。如何實現這一點?需要你的幫助。我需要將通知警報主體放在標籤或字符串處。

回答

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 
    } 
} 
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); 
} 
} 
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. 
} 
獲取數據
相關問題