Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user allowed local notifications or not. iOS 8. Obj-C

Is there no simple way of testing if the user has allowed local notifications? I noticed a warning in my console after I denied the sending of local notifications. When the relevant event occurred it said that the app tried to send a notifcation even though the user didn't allow it. I want to check if it's allowed before attempting to display a notification. See the comment in my condition, how do I do that?

My code is:

app = [UIApplication sharedApplication];
-(void)showBackgroundNotification:(NSString *) message {
//check if app is in background and check if local notifications are allowed.
    if (app.applicationState == UIApplicationStateBackground /*&& LocalNotificationsAreAllowed*/){
        UILocalNotification *note = [[UILocalNotification alloc]init];
        note.alertBody = message;
        note.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.0];
        [app scheduleLocalNotification :note];
    }
}

I get prompt the user for permission like so:

UIUserNotificationSettings *settings;
if ([app     respondsToSelector:@selector(registerUserNotificationSettings:)])
{
    settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotification    TypeSound) categories:nil];
    [app registerUserNotificationSettings:settings];
}

couldn't I use settings object?

EDIT: I think I have solved it. This seems to work.

-(void)showBackgroundNotification:(NSString *) message {
    if (app.applicationState == UIApplicationStateBackground && [app currentUserNotificationSettings].types != UIUserNotificationTypeNone){
        UILocalNotification *note = [[UILocalNotification alloc]init];
        note.alertBody = message;
        note.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.0];
        [app scheduleLocalNotification :note];
    }
}
like image 668
VeryPoliteNerd Avatar asked Apr 12 '15 14:04

VeryPoliteNerd


1 Answers

Here's what I use for less specific situations:

+ (BOOL)notificationsEnabled {
    UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
    return settings.types != UIUserNotificationTypeNone;
}

I usually keep a set of these types of methods in a notification manager.

like image 160
Logan Avatar answered Sep 20 '22 12:09

Logan