关闭应用程序后,通知会立即弹出,有时会明显延迟

时间:2018-10-15 20:52:17

标签: ios swift notifications delay

我的目标是在用户退出应用后,每次更新Firebase数据库时都接收通知。主要问题是,每次我退出应用程序时,都会收到我已经看到的通知。点击通知后,通知和图标徽章不会消失。通知有时会明显延迟。我在放置在AppDelegate的“ applicationWillResignActive”方法中的Firebase观察器中对新消息使用观察器:

 func applicationWillResignActive(_ application: UIApplication) {

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        let curr = Auth.auth().currentUser?.uid

/* to and curr are UIDs of users (I am checking if a user is allowed to see the message, this shouldn't be the problem */

let val = (snap.value as? NSDictionary)?["body"] as? String ?? ""
        if to == curr  {

            ref.child("Users").queryOrderedByKey().observe(.value, with: { (snap) in
                for s in snap.children {
                   let w = s as! DataSnapshot
                    if w.key == from { 
                    let v = w.value as? NSDictionary

                        let name = v?["nickname"] as? String ?? "N/A"
                        self.notify(name: name, text: val)
                    }
                }
            })
        }

在块中,我调用此方法以显示通知:

 func notify(name: String, text:String){
     UNUserNotificationCenter.current().removeAllDeliveredNotifications()

    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["new-message"]) // l
    let un = UNMutableNotificationContent()
    un.title = "\(name)"
    un.body = "\(text)"


    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false) // at least 60 if repeating//
    let request = UNNotificationRequest(identifier: "new-message", content: un, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}

我已经尝试调用下面的方法来摆脱每个ViewController中viewWillAppear中收到的通知,但是没有成功。

func fixNotif(){
    NotificationCenter.default.addObserver(self, selector: #selector(self.resign), name: UIApplication.willResignActiveNotification, object: nil)
}

@objc func resign(){
    NotificationCenter.default.removeObserver(self)
}

谢谢您的时间。

0 个答案:

没有答案