didRegisterForRemoteNotificationsWithDeviceToken仅在用户允许推送通知时调用

时间:2018-07-28 12:35:12

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

当前,仅当用户在调用didRegisterForRemoteNotificationsWithDeviceToken之后单击“允许”时才调用回调UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }

我认为应该有一种始终获取用户APN令牌的方法,但是目前我仅在用户允许推送通知的情况下获取它。即使用户不允许,有没有办法始终获得APN令牌?

意图是将令牌用于静默通知,即使它们不允许显示通知也是如此

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    firstLaunchCheck()

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
    application.registerForRemoteNotifications()

    return true
}

// Called when APNs has assigned the device a unique token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Convert token to string
    let passedTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    //store token in db
    print("APNs device token: \(passedTokenString)")
}

1 个答案:

答案 0 :(得分:0)

经过数小时的挫败后设法解决了这个问题。我只需要在Xcode

功能部分的“后台模式”下启用“远程通知”即可。

enter image description here

现在,无论用户是否允许推送通知,我都将获得APN令牌