2015-11-17 2 views
0

У меня есть следующий код, который Im помощь, чтобы решить, если пользователь дал разрешения для локальных уведомлений:UIUserNotificationSettings не работает правильно?

UIUserNotificationSettings *grantedSettings = [[UIApplication sharedApplication] currentUserNotificationSettings]; 
if (grantedSettings.types == UIUserNotificationTypeNone) { 
     NSLog(@"No permission granted"); 
     //IF AND ONLY IF alerts are wanted by raymio user! FIX 
     UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Notice" 
                     message:@"You need to enable notifications to be able to receive sun alerts!" 
                   preferredStyle:UIAlertControllerStyleAlert]; 

     UIAlertAction* OKAction = [UIAlertAction actionWithTitle:@"Go to Settings now" style:UIAlertActionStyleDefault 
                 handler:^(UIAlertAction * action) { 
               NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; 
               [[UIApplication sharedApplication] openURL:url]; 
                 }]; 

     [alert addAction:OKAction]; 
     UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault 
                 handler:^(UIAlertAction * action) {}]; 

     [alert addAction:cancelAction]; 
     [self.window addSubview:self.window.rootViewController.view]; 
     [self.window makeKeyAndVisible]; 
     [self.window.rootViewController presentViewController:alert animated:YES completion:nil]; 
    } 
    else if (grantedSettings.types & UIUserNotificationTypeSound & UIUserNotificationTypeAlert){ 
     NSLog(@"Sound and alert permissions "); 
    } 
    else if (grantedSettings.types & UIUserNotificationTypeAlert){ 
     NSLog(@"Alert Permission Granted"); 

В принципе, это просто не работает. Я получаю «Предоставление разрешения на оповещение», когда переключатель разрешения уведомлений явно отключен в настройках приложения. Если я включу его, настройки не изменятся. Ниже представлен консольный вывод для предоставленных настроек. Он остается прежним. У меня есть другие случаи, когда что-то не работает. На данный момент я прибегаю к простому удалению кода. Я должен был сделать это в первую очередь, если пользователь случайно нажал кнопку отмены в первоначальном приглашении (и все же запросит оповещения в приложении).

granted settings: <UIUserNotificationSettings: 0x17042e940; types: (UIUserNotificationTypeAlert UIUserNotificationTypeBadge UIUserNotificationTypeSound);> 

Любое понимание этой багги области? Кстати, я работаю на 8.1. Потребность в этом не совсем то же самое на ios9, так как ios9 позволит пользователю запрашивать разрешение на уведомление более одного раза. Pr 0 ..

+0

Где 'generatedSettings' приходит? –

+0

@CharlesA Я пропустил одну строку, отредактировал вопрос – DevilInDisguise

ответ

0

Я использовал метод ниже в одном из своих проектов, чтобы определить, имеет ли пользователь с разрешения или нет, или действительно ли он отключил уведомления в настройках. Поместите этот метод в AppDelegate и проверить

-(BOOL)notificationServicesEnabled { 
     BOOL isEnabled = NO; 

     if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){ 
      UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings]; 

      if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) { 
       isEnabled = NO; 
      } else { 
       isEnabled = YES; 
      } 
     } else { 
      UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; 
      if (types & UIRemoteNotificationTypeAlert) { 
       isEnabled = YES; 
      } else{ 
       isEnabled = NO; 
      } 
     } 

     return isEnabled; 
    } 

Тогда вы можете просто проверить с условием

if([self notificationServicesEnabled]) 

Я надеюсь, что это должно помочь вам.

0

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

BOOL isEnabled = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications]; 
Смежные вопросы