我在AppDelegate中设置,如下所示:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format:"%02.2hhx", $0) }.joined()
        print("didRegisterForRemoteNotificationsWithDeviceToken got called - Token is: \(token)")
        // delegate might get called even before an authtoken has been set for the user. Return in such cases:
        guard UserDefaults.standard.string(forKey: "authtoken") != nil else {return}
        // otherwise continue:
        if (token != UserDefaults.standard.string(forKey: "apnsToken")) {
            self.apiService.setAPNSToken(apnsToken: token, completion: {result in
                switch result {
                case .success(let resultString):
                    DispatchQueue.main.async {
                        UserDefaults.standard.set(token, forKey: "apnsToken")
                        print(resultString, " Token is: \(token)")
                    }
                case .failure(let error):
                    print("An error occured \(error.localizedDescription)")
                }
            })
        } else {
            print("User is registered for Push Notifications. Token did not change and is: \(token)")
        }
    }我请求用户允许在我的一个视图控制器中发送推送通知,如下所示:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
            DispatchQueue.main.async {
                if (granted) {
                    UserDefaults.standard.set(true, forKey: "pushNotificationsEnabled")
                }
                print("permission granted?: \(granted)")
            }
        }我想都是相当标准的。我的困惑/问题是:不会在用户交互时被调用--也就是说,只要用户点击“允许推送通知”,它就会被调用,这样apns令牌就会存储在我的后端。但事实并非如此,当我关闭应用程序并重新启动它时,会调用并将令牌存储在后端。
当用户点击“允许推送通知”后,我需要做什么才能访问令牌并将其存储在后台?
发布于 2020-03-26 16:10:14
当您的用户确认他们想要通知时,您应该调用UIApplication.shared.registerForRemoteNotifications()。看起来你不是在这么做。
你可以这样做
UNUserNotificationCenter.current()
  .requestAuthorization(options: [.alert, .sound, .badge]) {
    [weak self] granted, error in
    print("Permission granted: \(granted)")
    guard granted else { return }
    self?.getNotificationSettings()
}然后,getNotificationSettings在注册远程通知之前检查它是否已被授权。
func getNotificationSettings() {
  UNUserNotificationCenter.current().getNotificationSettings { settings in
    print("Notification settings: \(settings)")
    guard settings.authorizationStatus == .authorized else { return }
    DispatchQueue.main.async {
       UIApplication.shared.registerForRemoteNotifications()
    }
  }
}有关如何处理推送通知的更多信息,请查看此Ray Wenderlich tutorial。
https://stackoverflow.com/questions/60862764
复制相似问题