【问题标题】:How to prevent pop up alert when receiving push notification and the app is in the foreground收到推送通知且应用程序在前台时如何防止弹出警报
【发布时间】:2020-12-28 14:51:22
【问题描述】:

我正在使用 Swift 制作一个 IOS 聊天应用程序。 当用户发送新消息时,所有其他用户都会收到推送通知。 当用户不使用该应用程序时,推送通知运行良好,但是当用户使用该应用程序并与其他用户聊天时,他会收到一个弹出警报,其中包含其他用户发送的每条消息。 我想阻止此弹出警报发生。

这是 AppDelegate.swift 中的代码

// MARK: - DELEGATES FOR PUSH NOTIFICATIONS
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let installation = PFInstallation.current()
        installation?.setDeviceTokenFrom(deviceToken)
        installation?.saveInBackground(block: { (succ, error) in
            if error == nil {
                print("DEVICE TOKEN REGISTERED!")
            } else {
                print("\(error!.localizedDescription)")
        }})
}
    
 
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}
    
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    PFPush.handle(userInfo)
    if application.applicationState == .inactive {
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(inBackground: userInfo, block: nil)
    }
}

这是我在视图控制器中编写的代码

let pushStr = "\(PFUser.current()![USER_FULLNAME]!): \(m["body"]!)"
                                let data = [ "badge" : "Increment",
                                            "alert" : pushStr]
                                let request = [
                                            "someKey" : id,
                                            "data" : data
                                ] as [String : Any]
                                PFCloud.callFunction(inBackground: "push", withParameters: request as [String : Any], block: { (results, error) in
                                    if error == nil {
                                        print ("\(pushStr)\n")
                                    } else {
                                        print ("\(error!.localizedDescription)")
                                }})

【问题讨论】:

  • 这不是我们在这里展示代码的方式。
  • 我编辑了问题并将代码以正确的格式放置。谢谢!

标签: ios swift xcode push-notification


【解决方案1】:

如果您使用的是UNUserNotificationCenter

添加此方法

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    if itIsChatAlert { //check by push userInfo
        completionHandler([])
    } else {
        completionHandler([.alert, .sound])
    }
}

【讨论】:

  • 我不使用这个功能。请问还有什么建议吗?
  • 如果你想让它工作,你应该使用它,是时候为 U 实现 UNUserNotificationCenter 了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
相关资源
最近更新 更多