Firebase listener when app is in the background

后端 未结 4 2097
逝去的感伤
逝去的感伤 2020-12-05 21:52

I have a Firebase childAdded event listener for the notifications table in my app that I would like to trigger push notifications when the app is in the backgro

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 22:50

    You can add background task to firebase observer

    @objc func observeNotificationsChildAddedBackground() {
    
          var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
    
          backgroundTask = UIApplication.shared.beginBackgroundTask {
               [unowned self] in
               UIApplication.shared.endBackgroundTask(backgroundTask)
               backgroundTask = UIBackgroundTaskInvalid
          }
          assert(backgroundTask != UIBackgroundTaskInvalid)
    
          self.notificationsBackgroundHandler = FIREBASE_REF!.child("notifications/\(Defaults.userUID!)")
    
          self.notificationsBackgroundHandler!.queryOrdered(byChild: "date").queryLimited(toLast: 99).observe(.childAdded, with: { snapshot in
    
               let newNotificationJSON = snapshot.value as? [String : Any]
    
               if let newNotificationJSON = newNotificationJSON {
    
                       let status = newNotificationJSON["status"]
    
                       if let status = status as? Int {
    
                       if status == 1 {
                          self.sendPushNotification()
                       }
                }
             }
         })
    }
    

提交回复
热议问题