Request authorization for remote notifications always return false at first start

Gor*_*hez 4 push-notification ios swift

request authorization for push notifications always return false when app is first loaded even user tap "allow" on dialog. Here is function for register which is called in didFinishLaunchingWithOptions. At next launch granted is true.

func registerForPushNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            print("Permission granted: \(granted)")
            guard granted else{return}
            self.getNotificationSettings()
        }
}
Run Code Online (Sandbox Code Playgroud)

ada*_*haU 6

在 didfinishLaunchingWithOptions 中注册远程通知并确保注册远程通知。

application.registerForRemoteNotifications()

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

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        guard granted else{return}

        self.getNotificationSettings()

    }
    application.registerForRemoteNotifications()
    return true
}
Run Code Online (Sandbox Code Playgroud)