【问题标题】:iOS FCM Push notifications not working in background state in swift?iOS FCM推送通知不能在后台快速工作?
【发布时间】:2018-03-22 07:53:16
【问题描述】:

在我的应用程序中,我实现了 FCM 推送通知。当使用 FCM 控制台和 pushtry.com 网站检查通知时,它工作正常,然后我尝试使用实际的服务器 API,前台通知运行良好,但后台通知没有收到,有时它很少收到,而且也没有横幅和声音。请帮助找出问题。

在这里我附上了我正在尝试的代码..

import UIKit
import UserNotifications
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication,
             didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()

Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
    UNUserNotificationCenter.current().delegate = self

    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
} else {
    let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
    application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, 
didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

print(userInfo)
}
func applicationDidBecomeActive(_ application: UIApplication)
{
    Messaging.messaging().shouldEstablishDirectChannel = true

    application.applicationIconBadgeNumber = 0;
}

func applicationDidEnterBackground(_ application: UIApplication)
{
    Messaging.messaging().shouldEstablishDirectChannel = false
    print("Disconnected from FCM.")
}
func application(_ application: UIApplication, 
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
             fetchCompletionHandler completionHandler: @escaping 
(UIBackgroundFetchResult) -> Void) {

print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, 
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \ . 
(error.localizedDescription)")
}
func application(_ application: UIApplication, 
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")

}
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter,
                        willPresent notification: UNNotification,
                        withCompletionHandler completionHandler: 
@escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
  print(userInfo)

completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                        didReceive response: UNNotificationResponse,
                        withCompletionHandler completionHandler: 
@escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
print(userInfo)

completionHandler()
}
}

extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didRefreshRegistrationToken 
fcmToken: String) {
  print("Firebase registration token: \(fcmToken)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: 
MessagingRemoteMessage) {
  print("Received data message: \(remoteMessage.appData)")
}
}

这里分享一下服务器推送通知的请求格式:

{
"to":"cerGBjsmtzE:APA91bFk- 
 6ZI4ehaWbg0bGSGzAh10NeUh3AcyEFq7dASU7W4YY4WL8vWCA5wav- 
 LTYc0xTGWHev8Z99",
 "priority":"high",
"data":
  {
    "title":"New Inspection scheduled",
    "body":"You have a new Inspection Request scheduled,
    "sound":"default"
  }
}

【问题讨论】:

标签: ios swift firebase push-notification firebase-cloud-messaging


【解决方案1】:

确保您在后台模式下选择了远程设置 --- 在 XCODE 的功能部分下

【讨论】:

    【解决方案2】:

    要在后台模式下接收推送通知,您的有效负载格式中必须存在具有值 "1"true"mutable-content" 键。

    请告诉您,后端开发人员,添加该密钥。 请检查以下有效载荷格式

    {
       "to": "dWB537Nz1GA:APA91bHIjJ5....",
       "content_available": true,
       "mutable_content": true,
    
       "data":
       {
          "message": "Offer!",
          "mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
       },
    
       "notification":
       {
          "body": "Enter your message",
          "sound": "default"
       }
    }
    

    您可以参考以下链接 https://firebase.google.com/docs/cloud-messaging/concept-options

    【讨论】:

    • 我想在哪里添加那个键兄弟。
    • 您的有效负载格式中也缺少通知键
    • 请查看我的回答
    • 在后端他们使用关键的“数据”而不是“通知”,这是否是正确的请求?
    • 不,安卓人需要数据密钥,ios人需要通知
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多