其他解决方案对我不起作用。
我想要一个向 iOS 和 Android 发送数据消息的解决方案。
从我的测试中我发现,当我的 iOS 应用程序在后台时可靠地发送数据消息的唯一方法是包含一个空的通知负载。
另外,正如其他答案所提到的,您需要包含content_available 和priority。
要使用 curl 命令对此进行测试,您需要您的 FCM server key 和来自应用的 FCM 令牌。
仅适用于 iOS 的 curl 命令示例。 (没有可见通知的可靠数据消息)
curl -X POST \
https://fcm.googleapis.com/fcm/send \
-H 'authorization: key=server_key_here' \
-H 'content-type: application/json' \
-d '{
"to": "fcm_token_here",
"priority": "high",
"content_available": true,
"notification": {
"empty": "body"
},
"data": {
"key1": "this_is_a_test",
"key2": "abc",
"key3": "123456",
}
}'
将上面的server_key_here 和fcm_token_here 替换为您自己的。
AppDelegate 类中的以下方法应在应用处于后台且不显示 UI 消息时调用。
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//get data from userInfo
completionHandler(UIBackgroundFetchResult.newData)
}
以下是使用云函数和打字稿发送到主题的方法。
const payload = {
notification: {
empty: "message"
},
data: {
key1: "some_value",
key2: "another_value",
key3: "one_more"
}
}
const options = {
priority: "high",
contentAvailable: true //wakes up iOS
}
return admin.messaging().sendToTopic("my_topic", payload, options)
.then(response => {
console.log(`Log some stuff`)
})
.catch(error => {
console.log(error);
});
以上内容似乎始终适用于 iOS,有时也适用于 Android。
我得出的结论是,我的后端需要在发送推送通知之前确定平台才能最有效。