检查用户是否允许本地通知。 iOS 8. Obj-C
如果用户允许本地通知,是否没有简单的测试方法?在我拒绝发送本地通知后,我在控制台中发现了一条警告。当相关事件发生时,它表示应用程序试图发送通知,即使用户不允许。我想在尝试显示通知之前检查它是否被允许。看到我的情况的评论,我该怎么做?检查用户是否允许本地通知。 iOS 8. Obj-C
我的代码是:
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];
}
}
我得到提示用户是否允许像这样:
UIUserNotificationSettings *settings;
if ([app respondsToSelector:@selector(registerUserNotificationSettings:)])
{
settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotification TypeSound) categories:nil];
[app registerUserNotificationSettings:settings];
}
我不能使用设置对象?
编辑:我想我已经解决了它。这似乎工作。
-(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];
}
}
下面是我用更少的具体情况:
+ (BOOL)notificationsEnabled {
UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
return settings.types != UIUserNotificationTypeNone;
}
我通常把一组这几种方法的通知经理。
我试着用** settings.types!= UIUserNotificationTypeNone **替换我的/ * */- 注释。可悲的是,它没有奏效。它仍然会尝试发送通知。另外我发现它令人困惑,称为_types_的东西包含一个数值(枚举是,但仍然)。这听起来更像是一个集合。 – VeryPoliteNerd
我一直在生产中使用这段代码一段时间,它总是可靠地进行测试。你确定没有其他事情了吗? – Logan
我只使用该功能发送通知。但我可能错误键入了一些内容。它现在工作。至少在模拟器上。 – VeryPoliteNerd
检查我的答案在这里:http://stackoverflow.com/a/33779144/1463604 – Nishant