簡體   English   中英

當應用程序在后台時處理 iOS 推送通知

[英]Handle iOS Push Notification when app in backgroud

當應用程序在后台/運行時,我必須處理推送。 我正在使用 firebase 和本機推送服務。 設置功能-后台獲取 我正在接收推送,當應用程序在后台運行時,我可以在推送視圖上打開應用程序錄音,並在應用程序運行時處理推送。 但我必須執行以下操作:

應用程序運行時。

接收推送,顯示警報,注銷用戶。 作品!

當應用程序在后台/關閉時。 從推送中打開應用程序。

didReceiveRemoteNotification方法中處理此操作。 作品!

當應用程序在后台/關閉時。 從應用程序圖標打開應用程序時。

didReceiveRemoteNotification方法中處理此操作。 不起作用! .

當應用程序在后台/關閉時如何獲得推送。 保存數據(例如徽章計數或推送可以在 AppDelegate 變量中)。 並在applicationDidBecomeActive方法中得到這個?

要處理推送通知,您需要實現兩種方法,一種在應用程序關閉時調用,一種在應用程序處於前台時調用。

extension AppDelegate: UNUserNotificationCenterDelegate {
   /// Called when the app receive the notification in foreground
   /// - Parameter center: <#center description#>
   /// - Parameter notification: <#notification description#>
   /// - Parameter completionHandler: <#completionHandler description#>
   func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
       let userInfo = notification.request.content.userInfo

       // Get aps object
       let aps = userInfo["aps"] as! [String : Any]
       // Do your stuff here

       // This line is NEEDED, otherwise push will not be fired
       completionHandler([.alert, .badge, .sound]) // Display notification depending on your needed
   }


   /// Detect when user tap on a push message when app is closed
   /// - Parameter center: <#center description#>
   /// - Parameter response: <#response description#>
   /// - Parameter completionHandler: <#completionHandler description#>
   func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

       let userInfo = response.notification.request.content.userInfo
       // Get aps object
       let aps = userInfo["aps"] as! [String : Any]
       // Do your stuff here

       // This line is NEEDED, otherwise push will not be fired
       completionHandler()
   }
}

並在您的didFinishLaunchingWithOptions中將您的 AppDelegate 設置為委托:

// Set AppDelegate as UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().delegate = self

希望這可以幫助:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM