Firebase Cloud Messaging PHP Rest API在iOS端无法正常工作求助
解决iOS无法接收FCM自定义负载通知的问题
嘿,我来帮你搞定这个iOS收不到通知的问题!你的代码在Android上正常,但iOS不行,核心原因是FCM对iOS和Android的消息结构要求不一样——控制台发送的通知默认包含了iOS系统需要的notification字段,而你的代码只发了data负载,这就导致iOS系统不会自动弹出通知(纯data消息需要App在前台或通过后台机制主动处理)。
问题分析
iOS系统处理FCM消息的逻辑:
- 如果消息包含
notification字段:无论App在前台/后台/未启动,系统都会自动弹出通知栏消息。 - 如果只有
data字段:只有当App处于前台时,才会触发App内的回调;后台/未启动时,系统不会主动显示通知,需要额外配置后台唤醒权限。
另外你代码里把priority、content_available这些顶级FCM参数放在了data字段里,这也是无效的,这些参数需要放在外层。
修改后的代码
下面是调整后的完整函数,我添加了notification字段,修正了参数位置,并优化了iOS适配:
public function send_notification($registatoin_ids, $message, $title, $sound, $purpose) { // Set POST variables $url = 'https://fcm.googleapis.com/fcm/send'; $fields = array( 'registration_ids' => $registatoin_ids, // 添加iOS需要的notification字段,确保系统能自动弹出通知 'notification' => array( "title" => $title, "body" => $message, "sound" => $sound ?: "default", // 无自定义音效时用系统默认 "badge" => 1 // 可选:设置App图标角标,需在App内处理清零逻辑 ), 'data' => array( "for" => $purpose, "id" => strtotime("now"), "message" => $message, "title" => $title, "sound" => $sound, "vibrate" => 1, "date" => date("D d, M Y h:i A") ), // 把FCM顶级参数移到外层,确保生效 'priority' => 'high', 'content_available' => true, // 开启后可唤醒后台处理data(需iOS配置后台模式) 'time_to_live' => 600, ); $headers = array( 'Authorization: key=' . FCM_API_KEY, 'Content-Type: application/json' ); // Open connection $ch = curl_init(); // Set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); // Execute post $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } // Close connection curl_close($ch); return $result; }
额外的iOS配置注意事项
- 开启后台通知权限:在iOS项目的
Capabilities中,开启Background Modes并勾选Remote notifications,这样content_available: true才能生效,让App在后台唤醒处理data负载。 - 通知权限检查:确保用户已经给App开启了通知权限(可以在App启动时主动请求权限)。
- 自定义音效:如果使用自定义音效,音频文件必须是iOS支持的格式(如.wav),且要添加到项目资源中,文件名要和
sound参数一致(无需加后缀)。 - 前台通知处理:如果App处于前台,iOS不会自动弹出通知,你需要在
AppDelegate的didReceiveRemoteNotification方法中手动创建本地通知显示。
这样修改后,iOS应该就能正常收到通知了,同时Android端的功能也不会受影响~
内容的提问来源于stack exchange,提问作者Mudassir Shah
相关产品推荐
相关产品推荐

