【问题标题】:Swift how to detect when push notification permission is changed from system settings?Swift如何检测推送通知权限何时从系统设置更改?
【发布时间】:2020-02-08 18:50:41
【问题描述】:

用户安装应用并点击“不允许”并拒绝推送通知。 当应用程序处于活动状态时,用户转到系统设置并授予推送通知,然后返回应用程序。

当应用程序将要激活并调用注册推送通知时,如何检测设置通知权限已更改?

【问题讨论】:

  • 您应该始终注册推送通知。注册成功后会接到didRegisterForRemoteNotificationsWithDeviceToken的电话
  • @Paulw11 我明白这一点,但我如何才能检测到该用户更改权限?还是每次应用applicationDidBecomeActive注册推送的时候?
  • 您只需在每次启动时注册推送。如果在任何时候,用户授予权限,didRegisterForRemoteNotificationsWithDeviceToken 将被调用。

标签: ios swift push-notification apple-push-notifications


【解决方案1】:

对于 iOS 10.0 及更高版本,您可以使用UNUserNotificationCenter

你需要导入这个

import UserNotifications

然后用户关注以获取您应用的通知设置。

let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in

    if(settings.authorizationStatus == .authorized) {
        print("Push notification is enabled")
    } else {
        print("Push notification is not enabled")
    }
}

【讨论】:

  • 我应该在哪里称呼它?
  • 您可以在 AppDelegate 中调用它来检查用户是否启用了通知。
  • 但是当用户从后台 AppDelegate 方法调用应用程序时没有触发
  • 您可以根据自己的要求进行操作。理想情况下,我们从 AppDelegate 的 didFinishe... 方法中调用它。根据您的要求,您可以根据需要调用它。比如视图控制器类的viewDidLoad
【解决方案2】:

您可以使用相同的代码检查它AppDelegates 的didBecomeActive 事件。每次应用从后台状态进入前台状态时都会调用 didBecomeActive 事件。

let center = UNUserNotificationCenter.current()

center.getNotificationSettings { (settings) in

if(settings.authorizationStatus == .authorized) {
    print("Push notification is enabled")
} else {
    print("Push notification is not enabled")
}

}

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多