web-dev-qa-db-fra.com

détecter "Autoriser les notifications" est activé/désactivé pour iOS8

J'essaie de détecter les paramètres de notification locaux pour l'application dans iOS 8

pour UIUserNotificationSettings, il me renvoie 7 car j'ai activé tous les badges, sons et alertes.

Dans le contexte, je désactive "Autoriser la notification", l'application me renvoie toujours 7 pour UIUserNotificationSettings (Badge, Son et alerte activés). Existe-t-il un moyen de détecter l'activation/la désactivation de "Autoriser Notification"? 

- (void)application:(UIApplication *)application
    didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{

    NSLog(@"---notificationSettings.types %d" , notificationSettings.types );
    if(notificationSettings.types!=7){
        UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:@"Please turn on Notification"
                                                         message:@"Go to Settings > Notifications > App.\n Switch on Sound, Badge & Alert"
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles: nil];
        [alert show];
    }
}
41
JosephT

La méthode enabledRemoteNotificationTypes est obsolète depuis iOS8.

Pour vérifier l'état des notifications à distance dans iOS8, vous pouvez appeler 

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications];

il retournera NON si l'utilisateur désactive les notifications dans les paramètres. Documentation on isRegisteredForRemoteNotifications

Ou vous pouvez récupérer tous les paramètres de notification actuels:

[[UIApplication sharedApplication] currentUserNotificationSettings];

Documentation on currentUserNotificationSettings

22
Ponf

Swift 3+

let isRegisteredForLocalNotifications = UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false

Swift 2.3

let isRegisteredForLocalNotifications = UIApplication.sharedApplication().currentUserNotificationSettings()?.types.contains(UIUserNotificationType.Alert) ?? false
14
Adam Smaka

Je m'excuse pour cette réponse/commentaire s'il est au mauvais endroit. Je suis VRAIMENT novice en programmation iOS et je n'ai jamais posté de débordement de pile auparavant. Je pense que cela devrait en fait être un commentaire, mais sans note 50, je ne suis pas autorisé. Je m'excuse également si l'explication est quelque peu rudimentaire, mais encore une fois, genre de nouveau :).

Je souhaitais également vérifier si un utilisateur avait modifié les notifications autorisées/requises par mon application après la demande initiale. Après avoir essayé de déchiffrer la documentation Apple (les rédacteurs d’Apple sont beaucoup plus intelligents que moi, ou la documentation est délibérément obscure) et après avoir testé un peu, j’ai testé la valeur de 

[[UIApplication sharedApplication] currentUserNotificationSettings].hash.

Je pense que cela renvoie une valeur de hachage de trois bits, le premier étant réservé aux notifications de bannière, le second aux notifications sonores et le troisième aux notifications d’alerte. 

Alors...

000 = 0 = no notifications.
001 = 1 = only banner,
010 = 2 = only sound,
011 = 3 = sound and banner, no alert
100 = 4 = only alert notifications
and so on until,
111 = 7 = all notifications on.

Cela indique également 0 si Autoriser les notifications est désactivé dans l'application Réglages . J'espère que cela vous aidera.

12
mebeDB

Pour vérifier l'état des notifications à distance dans iOS8 et iOS9, appelez:

// Obj-C
[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]; 
// Swift
UIApplication.sharedApplication().isRegisteredForRemoteNotifications

Il retourne true si votre application peut recevoir des notifications à distance. Toutefois, recevoir notifications à distance ne signifie pas que cela sera également afficher à l'utilisateur.

La requête registerForRemoteNotifications() aboutit dans presque tous les cas et la variable didRegisterForRemoteNotificationsWithDeviceToken de AppDelegate est appelée, ce qui vous donne le jeton de périphérique. L'application peut alors recevoir silencieux _ notifications à distance qui ne sont pas affichées à l'utilisateur. Vous pouvez par exemple déclencher des processus d’arrière-plan dans l’application lorsqu’une telle notification est reçue .. Voir Documentation .

Pour recevoir non seulement mais aussi afficher notifications à distance à l'utilisateur pour lequel vous demandez une autorisation avec:

// Swift
let notificatonSettings = UIUserNotificationSettings(forTypes: [.Badge, .Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificatonSettings)

Cela affichera une boîte de dialogue à l’utilisateur où il pourra accepter ou refuser votre demande. Indifférent de leur décision, l'application pourra toujours recevoir des notifications à distance.

Si les utilisateurs le permettent, la variable didRegisterForRemoteNotificationsWithDeviceToken de AppDelegate est appelée.

Pour vérifier si l'utilisateur a autorisé ou refusé votre demande ou si, en fait, vous avez modifié les autorisations de notification dans le paramètre iOS que vous appelez, procédez comme suit:

// Obj-C
[[UIApplication sharedApplication] currentUserNotificationSettings];
// Swift
UIApplication.sharedApplication().currentUserNotificationSettings()   

Voir Documentation .

11
Manuel

Cela devrait fonctionner la toute première fois que votre application est lancée. L'utilisateur obtiendra une boîte de dialogue. Pour vérifier si l'utilisateur refuse ou autorise les notifications, utilisez:

-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:   (UIUserNotificationSettings *)notificationSettings
{
    if (notificationSettings.types) {
        NSLog(@"user allowed notifications");
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }else{
        NSLog(@"user did not allow notifications");
        // show alert here
    }
}

Lors de lancements consécutifs, utilisez:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
9
Denis Kanygin

Swift 2

Dans AppDelegate:

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {

    if (notificationSettings.types == .None){ // User did NOT allowed notifications


    }else{ // User did allowed notifications


    }

}

De tout autre ViewController:

    if UIApplication.sharedApplication().currentUserNotificationSettings()!.types.contains(.None){

    }else{

    }
2
Marie Amida
UIUserNotificationType notificationType = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];

if(notificationType == UIRemoteNotificationTypeNone)
        {

            NSLog(@"OFF");
        }
        else{

            NSLog(@"ON");
        }

travaille pour moi

2
Sagar In

Vous pouvez contrôler la valeur de hachage de UIApplication.sharedApplication().currentUserNotificationSettings().

if(UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:"))){
        if(UIApplication.sharedApplication().currentUserNotificationSettings().hashValue == 0){
            pushNotificationStatus = "false"
        } else {
            pushNotificationStatus = "true"
        }
}
2
ACengiz

Utiliser .isRegisteredForRemoteNotifications() ne fonctionne pas (bien que ce soit le cas). Toutefois, lorsque les notifications sont désactivées ou que l'un des types n'est pas présent, le code suivant fonctionne.

func notificationsAreOk() -> Bool {
    let wishedTypes = UIUserNotificationType.Badge |
        UIUserNotificationType.Alert |
        UIUserNotificationType.Sound;
    let application = UIApplication.sharedApplication()
    let settings = application.currentUserNotificationSettings()
    if settings == nil {
        return false
    }
    if settings.types != wishedTypes {
        return false
    }
    return true
}

EDIT: après certains tests, cela ne fonctionne pas toujours lorsque les notifications sont désactivées. J'envisage d'envoyer une notification de test pour savoir quand ils fonctionnent.

0
AsTeR

regarde ça. le code est essayé et testé.

- (BOOL)isUserNotificationAllowed {
    UIUserNotificationType types = [[UIApplication sharedApplication] currentUserNotificationSettings].types;
    if(types & UIUserNotificationTypeBadge || types & UIUserNotificationTypeSound || types & UIUserNotificationTypeAlert){
        return YES;
    }
    else {
        return NO;
    }
}
0
Irfan Gul