2016-01-08 4 views
0

Я пытаюсь внедрить службу уведомлений Apple Push в своем приложении. Я следовал за Pushbots tutorial, но можно ли получить информацию из уведомления и поместить ее в таблицу?Как поместить информацию о полученном уведомлении в UITableView в приложении?

Единственный код, который я добавил в мой проект, находится в файле AppDelegate.m.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    [Pushbots sharedInstanceWithAppId:@"--my app id--"]; 
    [[Pushbots sharedInstance] receivedPush:launchOptions]; 
    return YES; 
} 

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    // This method will be called everytime you open the app 
    // Register the deviceToken on Pushbots 
    [[Pushbots sharedInstance] registerOnPushbots:deviceToken]; 
} 
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{ 
    NSLog(@"Notification Registration Error %@", [error userInfo]); 
} 

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { 
    //Handle notification when the user click it while app is running in background or foreground. 
    [[Pushbots sharedInstance] receivedPush:userInfo]; 
} 
+0

Я сделал то же самое, что вы хотите сделать здесь, я разместил свой ответ ниже. Пинг меня, если тебе нужна дополнительная помощь. –

ответ

0

userInfo - словарь, содержащий push-уведомления. aps - это ключ для тела push push.

Сохраните полезную нагрузку в NSUserDefaults, а затем используйте его в ViewController для заполнения таблицыView.

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
    { 
       // you can get the required message as below 
       NSString *msg = [userInfo valueForKey:@"aps"]; 
       NSLog(@"Push Notification:%@",msg); 

       [[NSUserDefaults standardUserDefaults]setObject:msg forKey:@"ReceivedNotifications"]; 
       //This is how you save object in NSUserDefaults 
    } 

Теперь в вашем ViewController.m

{ 
NSMutableArray *notificationArray= [NSMutableArray alloc]init]; 
notificationArray= [[NSUserDefaults standardUserDefaults]objectForKey:@"ReceivedNotifications"]; 
} 

Загрузите Tableview с помощью этого notificationArray.

+0

Извините, я не знаком с NSUserDefaults. Как я могу назвать его в ViewController? – Jay

+0

Я отредактировал ответ для вашего удобства. –

+0

Вы попробовали? –

0

Всякий раз, когда уведомление будет получено, didReceiveRemoteNotification будет вызываться с полезной нагрузкой (т.е. информацией о пользователе) .Вы может использовать разбор полезной нагрузки и показать его табличном

1

Пожалуйста, добавьте следующий код в ваш проект.

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
[[NSUserDefaults standardUserDefaults] setObject:[[userInfo objectForKey:@"aps"] objectForKey: @"id"] forKey:@"pushstring"]; 
[[NSUserDefaults standardUserDefaults]synchronize]; 
[[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo]; 
[UIApplication sharedApplication].applicationIconBadgeNumber = [[[userInfo objectForKey:@"aps"] objectForKey: @"badgecount"] intValue]; 

NSLog(@"value of array is %@",userInfo); 
//NSMutableArray *arr=[[NSMutableArray alloc]init]; 

// [arr addObject:[[userInfo valueForKey:@"aps"]valueForKey:@"category"]]; 
NSLog(@"value of array is %d",[[[userInfo objectForKey:@"aps"] objectForKey: @"badgecount"] intValue]); 
// for (arr in userInfo) { 
//  NSLog(@"key: %@, value: %@", arr, [userInfo objectForKey:arr]); 
// } 
// NSLog(@"value of alert is %@",[arr objectAtIndex:2]); 
// NSLog(@"value of category is %@",[[arr objectAtIndex:0]objectAtIndex:2]); 

} 

Надеюсь, это вам поможет.

+0

Это выводит на консоль. Как передать информацию в ViewController, чтобы поместить ее в таблицу и отобразить ее на экране пользователя? – Jay

0

Да, когда вы получаете уведомление в методе didReceiveRemoteNotification, вы получите полезную нагрузку от userinfo, чтобы вы могли изменять таблицу с данными.