【问题标题】:Check if user allowed local notifications or not. iOS 8. Obj-C检查用户是否允许本地通知。 iOS 8. Obj-C
【发布时间】:2015-04-12 14:20:36
【问题描述】:

有没有简单的方法来测试用户是否允许本地通知?在我拒绝发送本地通知后,我注意到控制台中出现警告。当相关事件发生时,它表示应用程序尝试发送通知,即使用户不允许。我想在尝试显示通知之前检查它是否被允许。在我的情况下看到评论,我该怎么做?

我的代码是:

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];
    }
}

【问题讨论】:

标签: ios ios8 uilocalnotification


【解决方案1】:

这是我在不太具体的情况下使用的:

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

我通常在通知管理器中保留一组这些类型的方法。

【讨论】:

  • 我尝试用 settings.types != UIUserNotificationTypeNone 替换我的 /* */-comment。可悲的是它没有用。它仍然尝试发送通知。此外,我发现称为 types 的东西包含一个数字值(枚举是但仍然)令人困惑。听起来更像是一个集合。
  • 我在生产环境中使用这段代码已经有一段时间了,它总是经过可靠的测试。你确定没有其他事情发生吗?
  • 我只使用那个功能来发送通知。但我可能打错了一些东西。它现在确实有效。至少在模拟器上。
  • 这不是一个好的检查。它会告诉您在UIUserNotificationType.allZeros 的情况下启用了通知。最好使用settings.types.rawValue & UIUserNotificationType.Sound.rawValue != 0。更多:stackoverflow.com/questions/26051950/…
  • @SimplGy - UIUserNotificationType.allZeros 就 Objective-C 而言将等于 UIUserNotificationType.None,但是,allZeroes 在 ObjC 中不存在,所以没有问题。在 swift 中,它们的原始值也相等(2.0 之前)。但是,在 Swift 2 中,.allZeroes 不存在。这个答案仍然完全有效。
猜你喜欢
  • 2014-11-21
  • 2014-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多