iOS 应用程序未收到 FCM 负载发送的数据消息
我正在尝试使用 Laravel 框架从 fcm 有效负载发送数据消息,如下所示。
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)
->setContentAvailable(true)
->setCollapseKey('collapse_all');
$option = $optionBuilder->build();
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData([
'name'=> 'pushDataUpdate',
'time'=> $message['time'],
'location'=> $message['location'],
'queue'=> $message['queue']
]);
$data = $dataBuilder->build();
$token = $fcm_token;
$downstreamResponse = FCM::sendTo($token, $option, null, $data);
$dataSent = array(
"title" => 'Update Data',
"fcm_success" => $downstreamResponse->numberSuccess(),
"fcm_failure" => $downstreamResponse->numberFailure(),
"fcm_modification" => $downstreamResponse->numberModification(),
"token_to_delete" => $downstreamResponse->tokensToDelete(),
"token_to_modify" => $downstreamResponse->tokensToModify(),
"token_to_retry" => $downstreamResponse->tokensToRetry(),
"token_to_error" => $downstreamResponse->tokensWithError()
);
有效负载数据响应在 Android 中传回。
Message data payload: {name=pushDataUpdate, time=10/3/2022, location=End, queue=End}
Message data payload size more than 0
当我尝试在 iOS 应用程序中调用此数据消息时,它不会返回,但会在 Android 应用程序中返回。我看到网上很多答案都说返回时会调用didReceiveRemoteNotification func。但是,我的情况是当我打开应用程序、关闭应用程序或终止应用程序时,数据消息没有传回。
以下是该应用程序的应用程序委托代码
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
sleep(1)
}
FirebaseApp.configure()
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().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()
NotificationCenter.default.addObserver(self, selector: #selector(removeBadgeNumber), name: UIApplication.willEnterForegroundNotification, object: nil)
Messaging.messaging().delegate = self
UIApplication.shared.applicationIconBadgeNumber = 0
return true
}
@objc func removeBadgeNumber() {
UIApplication.shared.applicationIconBadgeNumber = 0
print("badge: \(UIApplication.shared.applicationIconBadgeNumber)")
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions : Set<UISceneSession>) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Notification click opened")
let pushNotification = PushNotification()
let userInfo = response.notification.request.content.userInfo
let title = userInfo["title"] as! String
pushNotification.navigate(with: title)
print(userInfo)
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Foreground notification")
completionHandler([.alert,.badge,.sound])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
-> Void) {
if let name = userInfo["name"]{
if(name as? String == "pushDataUpdate"){
var info = [String: Any]()
info["location"] = userInfo["location"]
info["time"] = userInfo["time"]
info["queue"] = Int(userInfo["queue"] as! String)
NotificationCenter.default.post(name: Notification.Name(rawValue: DATA_NOTIFICATION), object: nil, userInfo: info)
}
}
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate{
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
我可以知道我编码错误的哪些步骤吗?
我可以从 firebase 获取通知传递,但不能获取数据消息。
我在这部分挣扎了好几天,希望有人能帮助我。
提前谢谢您!
I am trying to send data message from fcm payload by using Laravel framework as shown below.
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20)
->setContentAvailable(true)
->setCollapseKey('collapse_all');
$option = $optionBuilder->build();
$dataBuilder = new PayloadDataBuilder();
$dataBuilder->addData([
'name'=> 'pushDataUpdate',
'time'=> $message['time'],
'location'=> $message['location'],
'queue'=> $message['queue']
]);
$data = $dataBuilder->build();
$token = $fcm_token;
$downstreamResponse = FCM::sendTo($token, $option, null, $data);
$dataSent = array(
"title" => 'Update Data',
"fcm_success" => $downstreamResponse->numberSuccess(),
"fcm_failure" => $downstreamResponse->numberFailure(),
"fcm_modification" => $downstreamResponse->numberModification(),
"token_to_delete" => $downstreamResponse->tokensToDelete(),
"token_to_modify" => $downstreamResponse->tokensToModify(),
"token_to_retry" => $downstreamResponse->tokensToRetry(),
"token_to_error" => $downstreamResponse->tokensWithError()
);
Payload Data Response pass back in Android.
Message data payload: {name=pushDataUpdate, time=10/3/2022, location=End, queue=End}
Message data payload size more than 0
When I try to call this data message in iOS app it does not come back but it does come back in Android app. I saw that many online answer says that it will call didReceiveRemoteNotification func when coming back. However, my case is the data message did not pass back when I open the app, close the app or kill the app.
Below are my App Delegate code for the app
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
sleep(1)
}
FirebaseApp.configure()
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().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()
NotificationCenter.default.addObserver(self, selector: #selector(removeBadgeNumber), name: UIApplication.willEnterForegroundNotification, object: nil)
Messaging.messaging().delegate = self
UIApplication.shared.applicationIconBadgeNumber = 0
return true
}
@objc func removeBadgeNumber() {
UIApplication.shared.applicationIconBadgeNumber = 0
print("badge: \(UIApplication.shared.applicationIconBadgeNumber)")
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions : Set<UISceneSession>) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("Notification click opened")
let pushNotification = PushNotification()
let userInfo = response.notification.request.content.userInfo
let title = userInfo["title"] as! String
pushNotification.navigate(with: title)
print(userInfo)
completionHandler()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("Foreground notification")
completionHandler([.alert,.badge,.sound])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
print("Registration succeeded!")
print("Token: ", token)
}
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult)
-> Void) {
if let name = userInfo["name"]{
if(name as? String == "pushDataUpdate"){
var info = [String: Any]()
info["location"] = userInfo["location"]
info["time"] = userInfo["time"]
info["queue"] = Int(userInfo["queue"] as! String)
NotificationCenter.default.post(name: Notification.Name(rawValue: DATA_NOTIFICATION), object: nil, userInfo: info)
}
}
completionHandler(UIBackgroundFetchResult.newData)
}
}
extension AppDelegate{
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
May I know which steps that I code it wrong?
I can get the notification pass back from firebase but not the data message.
I am struggle at this part for days, hope anyone could help me with this.
Thank you in advanced!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论