在ViewController中请求通知。

时间:2018-08-10 21:26:10

标签: ios swift apple-push-notifications firebase-cloud-messaging

当前,我的应用程序在用户首次打开时立即向他们询问通知权限,当他们单击特定按钮时如何询问他们,以及当他们单击“是”时如何在该ViewController中运行registerForRemoteNotifications。以下是我的AppDelegate当前正在推广用户的位置。

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()

    UIApplication.shared.applicationIconBadgeNumber = 0

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    return true
}

2 个答案:

答案 0 :(得分:1)

将其放在ViewController中,然后在操作或ViewDidLoad中运行该函数。

func registerForRemoteNotification() {
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()

        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil{
                UIApplication.shared.registerForRemoteNotifications()
            }
        }

    }
    else {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}

答案 1 :(得分:0)

您需要在completionHandler中进行设置。

此行:UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in })

应该是:

UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: { granted, error in 
    if granted {
        application.registerForRemoteNotifications()
        // Do other things after user has been granted authorization
    }
})