【问题标题】:iOS8 - UILocalNotification, Check for permission later from codeiOS8 - UILocalNotification,稍后从代码中检查权限
【发布时间】:2014-09-20 06:25:46
【问题描述】:

我正在用 Swift for iOS8 编写我的应用程序。

我想使用 UILocalNotification 来通知用户一些事情。为此,我已在应用启动时请求许可:

application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil))

会出现一个确认框,请求许可。如果用户允许,就没有问题。

如果用户不授予权限,我如何检查是否从代码(以编程方式)启用了本地通知?

【问题讨论】:

    标签: swift ios8 uilocalnotification


    【解决方案1】:

    ..这就是你在 Swift 中检查它的方式:

    let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings()
    let required:UIUserNotificationType = UIUserNotificationType.Sound; // Add other permissions as required
    let notification = UILocalNotification()
    
        if (currentSettings.types & required) != nil {
            println("sound will come and also vibration")
            notification.soundName = UILocalNotificationDefaultSoundName
        }else{
            println("no sound no vibration")
        }
    

    很高兴知道:
    它会自动振动,无论声音是否通过您的 iPhone 按钮打开/关闭 - 如果用户在您的应用程序的设置中设置声音关闭,则不会发生任何事情。
    因此您不必另外添加振动。

    【讨论】:

    • notification.soundName 来自哪里?没有它,这行得通。谢谢。
    • @MKatleast3 - 哦,谢谢,我刚刚忘记添加 UILocalNotification 变量。在我的函数中,它有更多的行——我建议您准确地配置您的通知。 “if”框对我的解决方案非常重要。
    • 很好,谢谢!对于 Swift 3,考虑使用 --- if (currentSettings?.types.contains(required))! --- 而不是现在在 2 个 UIUserNotificationType 成员之间弃用的 & 运算符
    【解决方案2】:

    作为记录,这是您在 Objective-C 中检查权限的方式:

    UIUserNotificationSettings *current = [[UIApplication sharedApplication] currentUserNotificationSettings];
    UIUserNotificationSettings *required = UIUserNotificationTypeSound | UIUserNotificationTypeAlert; // Add other permissions as required
    if(current.types & required) {
        NSLog(@"Permission present: 0x%ulX", settings.types);
    } else {
        NSLog(@"Permission not present: 0x%ulX", settings.types);
    }
    

    【讨论】:

      【解决方案3】:

      documentation 这样回答你的问题:

      调用该方法后,应用调用其应用委托的application:didRegisterUserNotificationSettings:方法上报结果。您可以使用该方法来确定您的请求是被用户批准还是拒绝。

      【讨论】:

        【解决方案4】:

        来自documentation

        application.currentUserNotificationSettings()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-08-20
          • 1970-01-01
          • 1970-01-01
          • 2017-09-26
          • 1970-01-01
          • 2010-09-16
          • 1970-01-01
          相关资源
          最近更新 更多