UNUserNotificationCenter действительно получил ответ с обработчиком завершения, который никогда не называется iOS11, цель-C - PullRequest
0 голосов
/ 14 сентября 2018

Иногда один из моих пользователей сообщает, что не получает ни звука, ни баннера, который должен быть размещен, когда

  • (void) userNotificationCenter: (UNUserNotificationCenter *) center didReceiveNotificationResponse: (UNNotificationResponse *) ответ withCompletionHandler: (void (^) (void)) завершениеHandler

    вызывается системой. У меня есть внутренняя трассировка, которая выполняется на устройствах, которые получили мое приложение из App Store, и подтверждаю, что этот метод не вызывается. Трассировка также показывает, что в систему было отправлено несколько (64) запросов на уведомления. Я провел обширный поиск по этой проблеме, и все предложенные ответы отражают то, что я делаю в коде. Вот код в appDelegate, который устанавливает центр уведомлений и методы делегата (нерелевантный код пропущен, обозначен тремя точками). Буду признателен за любую помощь в решении этой проблемы.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
            // Override point for customization after application launch.
            NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
            UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    
            UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
            if (notification) {
    
                NSLog(@"application didFinishLaunching with UIApplicationLaunchOptionsLocalNotificationKey");
                [self applicationDidBecomeActive:application];
            }
    
    
            UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
            if (notification) {
                // run after a delay so that the cordova/kendo app has time to get ready
                //  [self performSelector:@selector(postNotification:) withObject:notification afterDelay:4.0];
                NSLog(@"application didFinishLaunching with UIApplicationLaunchOptionsLocalNotificationKey");
                [self applicationDidBecomeActive:application];
            }
    

...

  center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              // Enable or disable features based on authorization.
                              NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
                              if(granted == YES){
                                  [storage setBool:YES forKey:@"permission granted"];
                                  [storage setBool:YES forKey:@"alert permission granted"];
                                  [storage setBool:YES forKey:@"sound permission granted"];
                              }else{
                                  NSLog(@"No permission granted");
                                  [storage setBool:NO forKey:@"permission granted"];
                              };
                          }];

...

 #pragma mark UNNotificationCenter setup

    UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:@"ACCEPT_IDENTIFIER" title:NSLocalizedString(@"Continue notifications", nil) options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"DECLINE_IDENTIFIER" title:NSLocalizedString(@"Stop notifications", nil) options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction *doNotDisturbAction = [UNNotificationAction actionWithIdentifier:@"DO_NOT_DISTURB_IDENTIFIER" title:NSLocalizedString(@"Start Do Not Disturb", nil) options:UNNotificationActionOptionAuthenticationRequired];
    NSArray *actions = [NSArray arrayWithObjects:acceptAction, declineAction, doNotDisturbAction, nil];
    // NSArray *intentIdentifiers = [NSArray arrayWithObjects:@"none", nil];
    UNNotificationCategory *invite = [UNNotificationCategory categoryWithIdentifier:@"com.nelsoncapes.localNotification" actions:actions intentIdentifiers: @[] options:UNNotificationCategoryOptionNone];
    NSSet *categories = [NSSet setWithObjects:invite, nil];
    [center setNotificationCategories:categories];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              // Enable or disable features based on authorization.
                          }];

    [self setupWatchConnectivity];
    return YES

...

    #pragma mark UNNotification received in background
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"notification settings were changed");
        NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
        [storage setBool:YES forKey:KEventLoggerEventNotificationSettingsChanged];
        [storage synchronize];


        if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
            // Notifications not allowed
            NSLog(@"notification settings were changed");
            item.eventDescription = KEventLoggerEventNotificationsNotAllowed;

            // check settings for alert and sound
        }
       // UNNotificationSetting alertSetting = settings.alertSetting;
            if(settings.alertSetting == UNNotificationSettingEnabled){
                [storage setBool:YES forKey:@"alert permission granted"];
                item.eventDescription = KEventLoggerEventAlertsAreAllowed;
            }else{[storage setBool:NO forKey:@"alert permission granted"];
                item.eventDescription = KEventLoggerEventAlertsAreNotAllowed;
            }
            if (settings.soundSetting == UNNotificationSettingEnabled){
                [storage setBool:YES forKey:@"sound permission granted"];
                item.eventDescription = KEventLoggerEventSoundsAreAllowed;
            }else {[storage setBool:NO forKey:@"sound permission granted"];
                item.eventDescription = KEventLoggerEventSoundsAreNotAllowed;
            }

    }];
    NSLog(@"appdelegate - center didReceiveNotificationResponse");
    NSString *actionIdentifier = response.actionIdentifier;

    UNNotification *notification = response.notification;
    if([actionIdentifier isEqual:@"com.apple.UNNotificationDefaultActionIdentifier"] || [actionIdentifier isEqual:@"com.apple.UNNotificationDismissActionIdentifier"]){
    }else{


        BOOL accept = [actionIdentifier isEqual:@"ACCEPT_IDENTIFIER"];
        BOOL stop = [actionIdentifier isEqual:@"DECLINE_IDENTIFIER"];
        BOOL doNotDisturb = [actionIdentifier isEqual:@"DO_NOT_DISTURB_IDENTIFIER"];

        if (accept){NSLog(@"accept");
            [self handleAcceptActionWithNotification:notification];
        }
        else if (stop){NSLog(@"stop");
            [self handleDeclineActionWithNotification:notification];
        }
        else if(doNotDisturb) {NSLog(@"do not disturb");
            [self handleDoNotDisturbActionWithNotification:notification];
        };
    }

    completionHandler();
}

...

*#pragma mark UNNotification received in foreground
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"appdelegate willPresentNotification");
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        NSLog(@"notification settings were changed");
        NRCEventItem *item = [[NRCEventStore sharedStore]createItem];
        item.eventDateTime = [NSDate date];
        item.timeZone = [NSTimeZone localTimeZone];
        item.eventSender = [self description];

        NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];


        if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
            // Notifications not allowed
            NSLog(@"notification settings were changed");
            item.eventDescription = KEventLoggerEventNotificationsNotAllowed;
            // check settings for alert and sound
        }
        if(settings.alertSetting == UNNotificationSettingEnabled){
            [storage setBool:YES forKey:@"alert permission granted"];
            item.eventDescription = KEventLoggerEventAlertsAreAllowed;
        }else{[storage setBool:NO forKey:@"alert permission granted"];
            item.eventDescription = KEventLoggerEventAlertsAreNotAllowed;
        }
        if (settings.soundSetting == UNNotificationSettingEnabled){
            [storage setBool:YES forKey:@"sound permission granted"];
            item.eventDescription = KEventLoggerEventSoundsAreAllowed;
        }else {[storage setBool:NO forKey:@"sound permission granted"];
            item.eventDescription = KEventLoggerEventSoundsAreNotAllowed;
        }

    }];
    UNNotificationRequest * request = notification.request;
    NSString * actionIdentifier = request.identifier;
    if([actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier] || [actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]){
    }else{
            NSLog(@"app delegate notification received while in foreground");



            // remind the user
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notification", nil) message:@"Timer expired!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
            NSLog(@"app delegate willPresentNotificationWithCompletionHandler: dnd is not started");
        }else{
            NSLog(@"app delegate willPresentNotificationWithCompletionHandler: dnd has started");
            [center removeAllPendingNotificationRequests];
            [center removeAllDeliveredNotifications];
        }
    }



    completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);

}*
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...