简体   繁体   English

如何从 iOS Swift 5 中的应用设置启用推送通知?

[英]How to enable push notification from app settings in iOS Swift 5?

In my application I have in app settings for enabling/disabling push notifications.在我的应用程序中,我在应用程序设置中启用/禁用推送通知。 I ran into a case in which if user Don't allow notifications when the application launches and then enables it with Settings in the Application then authorization status is always Denied.我遇到了这样一种情况,如果用户在应用程序启动时不允许通知,然后使用应用程序中的设置启用它,那么授权状态总是被拒绝。

Here is my code for push notification in app delegate.这是我在应用程序委托中推送通知的代码。
I have called registerForPushNotifications method in didFinishLaunching.我在 didFinishLaunching 中调用了 registerForPushNotifications 方法。

// MARK: Register app for push notificaitons
    func registerForPushNotifications() {
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
          [weak self] granted, error in
          printLogs("Permission granted: \(granted)")
         // guard granted else { return }
            if error == nil {
                self?.getNotificationSettings()
            }

      }
    }

func getNotificationSettings() {
    UNUserNotificationCenter.current().getNotificationSettings { settings in
        printLogs("Notification settings: \(settings)")
        switch settings.authorizationStatus {
        case .authorized:
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        case .denied:
            printLogs("Notifications Denied")

        case .notDetermined:
            printLogs("Notifications not determined")
        default:
            break
        }

    }
}

and for enabling notifications from settings I am using this code为了从设置中启用通知,我正在使用此代码

 AppDelegate.shared.registerForRemoteNotifications()

Once a user has denied the permissions for push notifications, he has to enable them from within the settings app in order to get push notifications.一旦用户拒绝了推送通知的权限,他必须从设置应用程序中启用它们才能获得推送通知。 So on your settings screen, when user taps on enable notification option just take him to the notifications settings screen of your app.因此,在您的设置屏幕上,当用户点击启用通知选项时,只需将他带到您应用的通知设置屏幕。 And from there he can enable it.从那里他可以启用它。 Use this piece of code for opening settings app.使用这段代码打开设置应用程序。

if let bundle = Bundle.main.bundleIdentifier,
    let settings = URL(string: UIApplication.openSettingsURLString + bundle) {
    if UIApplication.shared.canOpenURL(settings) {
        UIApplication.shared.open(settings)
    }
}

After enabling from within the settings app, status won't be denied anymore.从设置应用程序中启用后,状态将不再被denied

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM