【问题标题】:applicationReceivedRemoteMessage only executes in foregroundapplicationReceivedRemoteMessage 仅在前台执行
【发布时间】:2017-03-12 07:02:30
【问题描述】:

我的项目使用 Firebase Notifications 作为其 APNs 服务,但我一直在使用 Firebase 控制台向我的设备发送通知作为测试,并且它们仅显示在前台(通过控制台输出)。当应用程序在后台或设备处于锁定屏幕时,设备不会收到任何通知。然而,当我打开应用程序备份时,控制台输出最终从 applicationReceivedRemoteMessage 方法到达。

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {

        print("%@", remoteMessage.appData)
        print("QQQQQ")
    }

示例输出:

%@ [AnyHashable("notification"): {
    body = Hi;
    e = 1;
}, AnyHashable("from"): 492525072004, AnyHashable("collapse_key"): org.myApp]
QQQQQ

【问题讨论】:

标签: ios swift firebase firebase-realtime-database firebase-cloud-messaging


【解决方案1】:

iOS 和数据消息有问题。它声明here

在 iOS 上,FCM 存储消息并仅在应用程序处于 前台并已建立 FCM 连接。

所以必须有一个解决方法。和我类似的东西:

发送 2 条推送通知:

1) 使用此代码在应用程序处于后台时唤醒用户电话/启动正常:

{
  "to" : "/topics/yourTopicName",
  "notification" : {
    "priority" : "Normal",
    "body" : "Notification Body like: Hey! There something new in the app!",
    "title" : "Your App Title (for example)",
    "sound" : "Default",
    "icon" : "thisIsOptional"
  }
}

2) 用户打开应用时触发的数据通知

{
  "to" : "/topics/yourTopicName",
  "data" : {
      "yourData" : "1",
      "someMoreOfYourData" : "This is somehow the only workaround I've come up with."
  }
}

因此,在- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage 方法下处理您的数据:

- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
// Print full message
NSLog(@"%@", remoteMessage.appData);
//
//*** ABOUT remoteMessage.appData ***//
// remoteMessage.appData is a Key:Value dictionary
// (data you sent with second/data notification)
// so it's up to you what will it be and how will the
// app respond when it comes to foreground.
}

我还会留下这段代码来触发应用程序内部的通知(创建本地通知),因为您可以使用它来创建一个静音横幅,所以即使应用程序进入前台,用户也会再次收到通知:

NSDictionary *userInfo = remoteMessage.appData;    
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.userInfo = userInfo;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = userInfo[@"yourBodyKey"];
localNotification.alertTitle = userInfo[@"yourTitleKey"];
localNotification.fireDate = [NSDate date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

它会在应用进入前台的同一秒触发通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 2016-08-09
    • 1970-01-01
    • 2023-03-21
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多