Кнопки действий в удаленном уведомлении iOS 10 (задача C) не приходят IIViewDeckController

После большого количества поисковых запросов и следования документу Apple я все еще не могу получить кнопку действия в удаленном (push) уведомлении, но я получаю ее в локальном уведомлении, следуя тому же коду для локального уведомления.

- (void)triggerAndRegisterNotification {

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
    // create actions
        #if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    // create actions
    UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:@"com.AG.yes"
                                                                              title:@"Save"
                                                                            options:UNNotificationActionOptionForeground];
    UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"com.AG.no"
                                                                               title:@"Decline"
                                                                             options:UNNotificationActionOptionDestructive];
    UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:@"com.AG.snooze"
                                                                              title:@"Snooze"
                                                                            options:UNNotificationActionOptionDestructive];
    NSArray *notificationActions = @[ acceptAction, declineAction, snoozeAction ];

    // create a category
    UNNotificationCategory *inviteCategory = [UNNotificationCategory categoryWithIdentifier:CYLInviteCategoryIdentifier actions:notificationActions intentIdentifiers:@[] options:UNNotificationCategoryOptionNone];

    NSSet *categories = [NSSet setWithObject:inviteCategory];

    // registration
    [center setNotificationCategories:categories];
    #endif
    } else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
    // create actions
    UIMutableUserNotificationAction *acceptAction = 
    [[UIMutableUserNotificationAction alloc] init];
    acceptAction.identifier = @"com.AG.yes";
    acceptAction.title = @"Accept";
    acceptAction.activationMode = 
    UIUserNotificationActivationModeBackground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO; //If YES requies 
    passcode, but does not unlock the device

    UIMutableUserNotificationAction *declineAction = 
    [[UIMutableUserNotificationAction alloc] init];
    declineAction.identifier = @"com.AG.no";
    acceptAction.title = @"Decline";
    acceptAction.activationMode = 
    UIUserNotificationActivationModeBackground;
    declineAction.destructive = YES;
    acceptAction.authenticationRequired = NO;

    UIMutableUserNotificationAction *snoozeAction = 
    [[UIMutableUserNotificationAction alloc] init];
    snoozeAction.identifier = @"com.AG.snooze";
    acceptAction.title = @"Snooze";
    snoozeAction.activationMode = 
    UIUserNotificationActivationModeBackground;
    snoozeAction.destructive = YES;
    snoozeAction.authenticationRequired = NO;

    // create a category
    UIMutableUserNotificationCategory *inviteCategory = 
    [[UIMutableUserNotificationCategory alloc] init];
    inviteCategory.identifier = CYLInviteCategoryIdentifier;
    NSArray *notificationActions = @[ acceptAction, declineAction, 
    snoozeAction ];

    [inviteCategory setActions:notificationActions 
    forContext:UIUserNotificationActionContextDefault];
    [inviteCategory setActions:notificationActions 
     forContext:UIUserNotificationActionContextMinimal];

    // registration
    NSSet *categories = [NSSet setWithObject:inviteCategory];
    UIUserNotificationType types = UIUserNotificationTypeBadge | 
    UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *settings = 
    [UIUserNotificationSettings settingsForTypes:types 
    categories:categories];
    [[UIApplication sharedApplication] 
    registerUserNotificationSettings:settings];
}
/// 2. request authorization for localNotification

        [self registerNotificationSettingsCompletionHandler:^(BOOL 
                                            granted, 
         NSError * _Nullable error) {
                         if (granted) {
                       NSLog(@"request authorization succeeded!");
        [[UIApplication sharedApplication] 
                   registerForRemoteNotifications];
       }
     }];

**COMMENTED CODE FOR LOCAL NOTIFICATION**

     //    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
     //     #if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
     //         Deliver the notification at 08:30 everyday
     // NSDateComponents *dateComponents = [[NSDateComponents 
                                                    alloc] init];
     // dateComponents.hour = 8;
     // dateComponents.minute = 30;
     // UNCalendarNotificationTrigger *trigger = 
     // [UNCalendarNotificationTrigger 
              triggerWithDateMatchingComponents:dateComponents 
              repeats:YES];        
     //        UNMutableNotificationContent *content = 
              [[UNMutableNotificationContent alloc] init];
      //        content.title = [NSString 
         localizedUserNotificationStringForKey:@"AG said:" 
         arguments:nil];
         //        content.body = [NSString 
         localizedUserNotificationStringForKey:@"Hello Tom!Get up, 
           let's play with Jerry!" arguments:nil];
         //        content.sound = [UNNotificationSound 
                                        defaultSound];
        //        content.categoryIdentifier = 
                             CYLInviteCategoryIdentifier;
       /// 4. update application icon badge number
       //        content.badge = @([[UIApplication sharedApplication] 
                                    applicationIconBadgeNumber] + 1);
      //        content.launchImageName = @"any string is ok,such as 
                                                    微博@iOS程序犭袁";
      // Deliver the notification in five seconds.
      //*** Terminating app due to uncaught exception 
           'NSInternalInconsistencyException', reason: 'time interval 
            must be at least 60 if repeating'
      //        UNTimeIntervalNotificationTrigger *trigger = 
                                   [UNTimeIntervalNotificationTrigger
      // triggerWithTimeInterval:60.0f repeats:YES];
      //        UNNotificationRequest *request = [ 
                UNNotificationRequest 
                        requestWithIdentifier:@"FiveSecond"
     //         content:content trigger:trigger];
     //        UNUserNotificationCenter *center = 
              [UNUserNotificationCenter currentNotificationCenter];
   /// 3. schedule localNotification,The delegate must be set before 
              the application returns from 
              applicationDidFinishLaunching:.
    // center.delegate = self;
     //        [center addNotificationRequest:request 
               withCompletionHandler:^(NSError * _Nullable error) {
     //            if (!error) {
    //                NSLog(@"add NotificationRequest succeeded!");
     //            }
    //        }];
   //#endif
    //    } else {
   /// 3. schedule localNotification
    //        UILocalNotification *localNotification = 
                        [[UILocalNotification alloc] init];
     //        localNotification.fireDate = [NSDate 
                             dateWithTimeIntervalSinceNow:5.f];
     //        localNotification.alertTitle = @"AG said:";
       //        localNotification.alertBody = @"Hello Tom!Get up, 
        let's play with Jerry!";
     //        localNotification.alertAction = @"play with Jerry";
    //Identifies the image used as the launch image when the user 
                     taps (or slides) the action button (or slider).
     //        localNotification.alertLaunchImage = 
                                      @"LaunchImage.png";
      //        localNotification.userInfo = @{ @"CategoryIdentifier" 
                      : CYLInviteCategoryIdentifier };
    //        
    //        localNotification.timeZone = [NSTimeZone 
                                defaultTimeZone];
    //repeat evey minute,  0 means don't repeat
   //        localNotification.repeatInterval = NSCalendarUnitMinute;
   /// 4. update application icon badge number
    //        localNotification.applicationIconBadgeNumber = 
              [[UIApplication sharedApplication] 
                   applicationIconBadgeNumber] + 1;
     //        [[UIApplication sharedApplication] 
                  scheduleLocalNotification:localNotification];
    //        
    //    }

  }

/// 3.  THIS IS THE METHOD TO AUTHORIZE THE NOTIFICATION


- (void)registerNotificationSettingsCompletionHandler:(void (^)(BOOL 
            granted, NSError *__nullable error))completionHandler; {
/// 2. request authorization for localNotification
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
    UNUserNotificationCenter *center = [UNUserNotificationCenter 
    currentNotificationCenter];
    [center requestAuthorizationWithOptions:
            (UNAuthorizationOptionBadge | UNAuthorizationOptionSound 
                                     | UNAuthorizationOptionAlert)
                          completionHandler:completionHandler];
 #endif
         } else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))  
  {
    //                UIUserNotificationSettings 
            *userNotificationSettings = [UIUserNotificationSettings 
             settingsForTypes:(UIUserNotificationTypeAlert | 
            UIUserNotificationTypeSound | 
                       UIUserNotificationTypeBadge)
    //                                                                                                         
                                 categories:nil];
    //                UIApplication *application = [UIApplication 
                                sharedApplication];
    //                [application 
          registerUserNotificationSettings:userNotificationSettings];
    //FIXME:
    // !completionHandler ?: completionHandler(granted, error);
   }
  }
**AND IN** APPDELEGATE.m
- (BOOL)application:(UIApplication *)application 
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
    /// schedule localNotification, the delegate must be set before 
 // the application returns fromapplicationDidFinishLaunching:.
    UNUserNotificationCenter *center = [UNUserNotificationCenter 
currentNotificationCenter];
    center.delegate = self;
#endif
  }
[self triggerAndRegisterNotification];
}

Я использую iphone 7 для тестирования. Пожалуйста, помогите мне решить эту проблему. Заранее спасибо

Полезная нагрузка JSon

             aps =     {
    alert =         {
        "artist_id" = 16912;
        body = "Kurt Rosenwinkel is playing at Joe Henderson Lab at 
        SFJAZZ Center";
        eventid = 149687805;
        sound = default;
        timestamp = "810b6035-e4d7-4722-81db-7455e81a48fe";
        title = "Kurt Rosenwinkel";
        tracks = "itunes,spotify";
        type = 2;
    };
    category = "com.wcities.notification";
   };

Я проверил, что идентификатор категории, который я установил в своем приложении, такой же, как и в полезной нагрузке json.

ОБНОВИТЬ

Когда я отлаживал и пришел к выводу, что из приведенного выше кода я получаю push-уведомление с кнопками действий, но где-то после did finish launching я меняю свой контроллер корневого представления Windows на контроллер представления, который является дочерним элементом IIViewDeckController. После комментирования этой строки приходит push-уведомление с кнопками действий. Я полностью сбит с толку, почему это происходит, потому что, насколько мне известно, не должно быть никакого влияния на push-уведомления, если я устанавливаю, представляю или нажимаю какой-либо контроллер просмотра.

пожалуйста, дайте мне знать, если я делаю какие-либо ошибки здесь. Я поделился всем кодом и сценарием выше. Спасибо




Ответы (2)


Поскольку я использую библиотеку док-станции, поэтому контроллеры просмотра, добавленные в контроллер представления док-станции, имели некоторый код, связанный с setting categories as nil. Это причина, по которой я не смог получить кнопку действия в удаленном уведомлении, поэтому я удаляю этот дополнительный код и все работает нормально. Я все еще нахожу того глупого человека, который написал этот код. Благодарю за помощь

person AG.29    schedule 30.05.2017

в ios 10 уведомления работают с -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{//код завершениеHandler(UNNotificationPresentationOptionAlert); }

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)ответ withCompletionHandler:(void(^)())completionHandler{ }

person trunghb    schedule 23.05.2017