2014-11-05 3 views
0

В настоящее время мое приложение получает уведомления об обновлениях в RSS-канал. Если пользователь открывает приложение из уведомления, он открывается на правильный контроллер представления. Если пользователь не подтверждает уведомление и открывает приложение из значка приложения, когда пользователь открывает меню в приложении, ячейка представления таблицы для этого rss-канала имеет значок значка с именем applicationIconBadgeNumber. После выбора этой строки значок на этой ячейке уходит, а номер приложения IconBadgeNumber сбрасывается. Мой вопрос заключается в желании отправлять уведомления о другой информации в приложении, например, о преимуществах членов. Как я могу отличить, какая строка в представлении таблицы получает значок? Скажите, что пользователь получает уведомление о пользе участника. Я хотел бы, чтобы значок появлялся в строке преимуществ членов табличного представления, но если есть уведомление из RSS-канала, значка соответствующей строки.Значок уведомлений в ячейке UITableView

Вот как я сейчас добавляю значок для строки RSS-ленты.

в cellForRowAtIndexPath:

if (!(indexPath.row == 0)) 
    { 
     cell.accessoryView = nil; 
    } 

    badgeNumber = [NSString stringWithFormat:@"%ld", (long)[[UIApplication sharedApplication]applicationIconBadgeNumber]]; 

    actionAlertBadge = [JSCustomBadge customBadgeWithString:badgeNumber withStringColor:[UIColor whiteColor] withInsetColor:[UIColor redColor] withBadgeFrame:NO withBadgeFrameColor:[UIColor redColor] withScale:1.0 withShining:NO withShadow:NO]; 
    actionAlertBadge.frame = CGRectMake(83, 6, 30, 30); 

    if ([badgeNumber isEqualToString:@"0"]) 
    { 
     actionAlertBadge.hidden = YES; 
    } 

    if (actionAlertBadge.hidden == NO) 
    { 
     if (indexPath.section == 0) 
     { 
      if (indexPath.row == 0) 
      { 
       cell.accessoryView = actionAlertBadge; 
      } 
     } 
    } 

в didSelectRowAtIndexPath:

if (indexPath.row == 0) 
     { 
      ActionAlertsViewController *actionAlerts = [[ActionAlertsViewController alloc]initWithStyle:UITableViewStylePlain]; 
      WebViewController *wvc = [[WebViewController alloc]init]; 
      [actionAlerts setWebViewController:wvc]; 
      [[UAPush shared] resetBadge]; 
      actionAlertBadge.hidden = YES; 
      [tableView reloadData]; 
      navController = [[KFBNavControllerViewController alloc]initWithRootViewController:actionAlerts]; 

      [UIView transitionWithView:appDelegate.window 
           duration:0.5 
           options:UIViewAnimationOptionTransitionFlipFromRight 
          animations:^{ 
           appDelegate.window.rootViewController = navController; 
          } 
          completion:nil]; 
     } 

EDIT: Вот как я пытаюсь сделать это, но он не работает, потому что моя NotificationType строка с моей точки зрения этой таблицы НОЛЬ.

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

    // Send the alert to UA so that it can be handled and tracked as a direct response. This call 
    // is required. 
    [[UAPush shared]appReceivedRemoteNotification:userInfo applicationState:application.applicationState]; 

    // Optionally provide a delegate that will be used to handle notifications received while the app is running 
    // [UAPush shared].delegate = your custom push delegate class conforming to the UAPushNotificationDelegate protocol 

    // Reset the badge after a push received (optional) 
    [[UAPush shared] resetBadge]; 

    NSDictionary *apsInfo = [userInfo valueForKey:@"aps"]; 

    NSString *alertMsg = @""; 

    if ([apsInfo valueForKey:@"alert"] != NULL) { 
     alertMsg = [apsInfo valueForKey:@"alert"]; 

     if ([alertMsg containsString:@"ACTION ALERT"]) { 
      notificationType = @"action alert"; 
     } 
     else if ([alertMsg containsString:@"MEMBER BENEFIT"]) { 
      notificationType = @"member benefit"; 
     } 
    } 
} 

cellForRowAtIndexPath:

KFBAppDelegate *appDelegate = (KFBAppDelegate *)[[UIApplication sharedApplication]delegate]; 
    NSString *notificationType = appDelegate.notificationType; 
    // NSLog(@"notificationType menu table: %@", notificationType); 
    badgeNumber = [NSString stringWithFormat:@"%ld", (long)[[UIApplication sharedApplication]applicationIconBadgeNumber]]; 
    actionAlertBadge = [JSCustomBadge customBadgeWithString:badgeNumber withStringColor:[UIColor whiteColor] withInsetColor:[UIColor redColor] withBadgeFrame:NO withBadgeFrameColor:[UIColor redColor] withScale:1.0 withShining:NO withShadow:NO]; 
    actionAlertBadge.frame = CGRectMake(83, 6, 30, 30); 

    if ([badgeNumber isEqualToString:@"0"]) { 
     actionAlertBadge.hidden = YES; 
    } 

    if (actionAlertBadge.hidden == NO) { 
     if ([notificationType isEqualToString:@"action alert"]) { 
      if (indexPath.section == 0) { 
       if (indexPath.row == 0) { 
        cell.accessoryView = actionAlertBadge; 
       } 
      } 
     } 
     else if ([notificationType isEqualToString:@"member benefit"]) { 
      if (indexPath.section == 0) { 
       if (indexPath.row == 5) { 
        cell.accessoryView = actionAlertBadge; 
       } 
      } 
     } 
    } 
+0

Вы можете выбрать в зависимости от свойств ячейки, например if (cell.title == @ "RSS") {сделать это}. –

+0

@FawadMasud, я это знаю. Проблема заключается в определении содержимого уведомления, поэтому правильная ячейка помечена значком. – raginggoat

ответ

0

Во-первых, при отправке уведомления, вы должны добавить поле типа в уведомлении. Вы получите JSon словарь как этот

{"aps":{"alert":{"type":"rss","text":"Hello, world!"},"sound":"default","badge":3}} 

Получить значение типа в функции (если приложение работает)

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary  *)dict {  
// get the type information out of the dictionary 
// now you can perform depending on this type. 
} 

Если приложение не работает, то в соответствии с apple's documentation

" Если приложение не запускается при поступлении push-уведомления, метод запускает приложение и предоставляет соответствующую информацию в словаре параметров запуска. Приложение не вызывает этот метод для обработки этого push-уведомления. Вместо этого ваша реализация application: willFinishLaunchingWithOptions: или application: didFinishLaunchingWithOptions: метод должен получить данные полезной нагрузки push-сообщения и ответить соответствующим образом. "

Получить словарь в приложение: didFinishLaunchingWithOptions: метод.

+0

См. Мое обновление. – raginggoat

+0

, чтобы обновить переменную «notificationType» в классе табличного представления, вы можете использовать методы делегатов или можете сохранить ее там, где она может быть доступна для всех классов, например. пользовательские настройки по умолчанию. –

+0

Я пытался использовать пользовательские настройки по умолчанию, но он по-прежнему не работает. Это похоже на то, что я делаю что-то неправильно в didReceiveRemoteNotification: но я не уверен, что. – raginggoat

0

В вашем AppDelegate, сначала свойство:

@property (nonatomic, copy) NSString *notificationType; 

Тогда в вашем

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 

использования:

self.notificationType = @"action alert"; 
self.notificationType = @"member benefit"; 

и в вашем CellForRowAtIndexPath:

if (actionAlertBadge.hidden == NO) { 
    if ([appDelegate.notificationType isEqualToString:@"action alert"]) { 
     .... 
    } 
    else if ([appDelegate.notificationType isEqualToString:@"member benefit"]) { 
     .... 
    } 

На боковой ноте я предлагаю попытаться воздержаться от сравнения строк и использовать что-то вроде перечислений.

+0

Это именно то, что я сделал. – raginggoat

+0

Вы уверены, что сохраняете тип уведомления в своем приложении appDelegate? потому что ваш код в вашем приложенииDidReceiveRemoteNotification, похоже, не подразумевает этого. (notificationtype = вместо self.notificationType). –

+0

Я изменил его на self.notificationType и он по-прежнему не работает. – raginggoat