如何在 swift 中修复'Multiple push notification'错误?



我正在通过关注一本书和一些关于推送通知的文档,在我的 iOS 应用程序上添加推送通知。

推送通知在

几天内工作正常,然后突然间我开始一次收到 3 个推送通知,然后逐渐增加到 7 个。


// this function is called from didFinishLaunchingWithOptions function
func requestForNotification(_ application: UIApplication){
      UNUserNotificationCenter.current().requestAuthorization(options: [.badge,.sound,.alert]) { (granted, _) in
           guard granted else {return}
           DispatchQueue.main.async {
               UIApplication.shared.registerForRemoteNotifications()
           }
       }
   }

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
       let token = deviceToken.reduce(""){$0 + String(format: "%02x",$1) }
       sendTokenToService(token: token)
       print("device token is:::::::::: (token)")
   }
//Send token to local server
func sendTokenToService(token:String){
       var params = [String:AnyObject]()
       params["token"] = token as AnyObject
       APIManager.shared.request(apiRouter: APIRouter.init(endpoint: .addAdminToken(param: params))) { (response, success) in
           if success, let response = response["response"] {
               print(response)
           }
       }
   }

registerForRemoteNotifications()只被调用一次,但我在苹果的官方文档中找到了这个:

registerForRemoteNotifications()方法:UIKit 可能会在其他极少数情况下调用它。例如,当用户从不是设备的备份数据还原设备后启动应用时,UIKit 调用该方法。在这种特殊情况下,应用在用户启动新设备的令牌之前不会知道它。

知道如何解决这个问题吗?

推送通知每device token传递一次。 如果您有权访问推送通知服务器(如果您不自己管理推送提供程序,则可以验证是否如此。 在设备上生成应用和安装时,新版本很可能会生成新令牌。 当用户卸载/安装应用时,也会发生这种情况。 这可能是您收到多个通知的原因。 Apple应该使旧设备令牌无效,并将反馈发送回您的服务器。 有关 Apple 如何向您发送反馈的更多信息,请访问其 Apple APNS 文档的链接。

最新更新