【问题标题】:How to turn on and off notifications in iOS?如何在 iOS 中打开和关闭通知?
【发布时间】:2017-07-28 15:13:05
【问题描述】:

我正在尝试在 iOS 11 应用程序中实现设置屏幕,我需要一个用于控制用户通知的 UISwitch。当设置为关闭时,我想放弃通知的权限,当设置为打开时,我想请求权限(标准对话框要求用户允许发送她的通知)。

为了请求许可,我找到了以下代码:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization.
}

但是,如果我在系统设置中关闭应用程序的通知,则此代码不会弹出带有请求的对话框,它只会在 granted 中返回 false。

我找不到任何关于如何放弃权限的信息。

关于如何解决问题的任何提示?有没有可能,或者 Apple 是否认为这个任务应该只留给系统设置?

【问题讨论】:

  • 仅限系统设置。原因很简单,用户不会在每次应用启动时被“推送通知请求”轰炸。一旦您获得发送通知的权限,您必须自己决定是否要向用户发送实际通知,也许添加用户可以选择加入/退出的主题。
  • 所以没有办法以编程方式放弃权限?
  • 您为什么要这样做?我不知道一种方法,这是没有意义的用例
  • 因为这个决定必须是用户的并且是唯一的。您不应该为用户决定他们是否要继续收到通知。此外,进行这样的设置是没有意义的,因为您作为程序员可以随时停止发送通知,从应用程序的角度来看,这与关闭它们相同。通知开关是在应用程序内部还是在系统中,对于这个特定问题没有影响。
  • 因为你是在要求用户给你权限,所以要求他撤销权限没有任何意义。您的应用程序可以决定不再向他发送通知,但这完全掌握在您手中,用户不应受到此决定的影响。

标签: ios swift unusernotificationcenter usernotifications


【解决方案1】:

在 iOS 中开启/关闭权限推送通知只出现一次。 所以为了实现这一点,你需要像你一样做一些调整 首先检查您的通知是否启用。

func pushEnabledAtOSLevel() -> Bool {
 guard let currentSettings = UIApplication.shared.currentUserNotificationSettings?.types else { return false }
 return currentSettings.rawValue != 0
}

之后,您可以使用打开/关闭按钮创建自定义弹出窗口 并导航到系统设置页面,用户可以在其中启用该选项 相应地

if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
    UIApplication.shared.openURL(appSettings as URL)
}

【讨论】:

    【解决方案2】:

    适用于 iOS 10.0 及更高版本

      UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            if settings.authorizationStatus == .authorized {
                // Notifications are allowed
            }
            else {
                // Either denied or notDetermined
    
                let alertController = UIAlertController(title: nil, message: "Do you want to change notifications settings?", preferredStyle: .alert)
    
                let action1 = UIAlertAction(title: "Settings", style: .default) { (action:UIAlertAction) in
                    if let appSettings = NSURL(string: UIApplication.openSettingsURLString) {
                        UIApplication.shared.open(appSettings as URL, options: [:], completionHandler: nil)
                    }
                }
    
                let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
                }
    
                alertController.addAction(action1)
                alertController.addAction(action2)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多