如何向多个设备发送推送通知?

23

这是我第一次在我的应用程序中使用推送通知。我已经查看了示例应用程序以及书籍,并了解了如何向单个设备发送推送通知。但是我不确定应该对我的程序做出什么更改才能向多个设备发送推送通知。我正在使用 'PushMeBaby' 应用程序进行服务器端编码。请帮我解决问题。


你可以在这里检查我所做的工作:https://dev59.com/gmUq5IYBdhLWcg3wXvMC - Subodh Ghulaxe
3个回答

31

试用这个示例代码并根据您的环境进行修改。

    $apnsHost = '<APNS host>';
    $apnsPort = <port num>;
    $apnsCert = '<cert>';

    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

    $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

    $payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
    $payload = json_encode($payload);

// Note: $device_tokens_array has list of 5 devices' tokens

    for($i=0; $i<5; $i++)
    {
            $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload;

            fwrite($apns, $apnsMessage);
    }?>

本文帮助验证断开连接和连接状态:Apple Push Notification: Sending high volumes of messages

其他参考链接:

如何在 iPhone 中一次性向多个设备发送推送通知? 以及 使用推送通知时如何处理多个设备?


谢谢回复!很高兴能够很快得到回复。但是我已经浏览了这些问题:( 我需要描述如何将所有设备令牌发送到我的服务器,然后如何在单个连接中向它们发送通知。这可能对您来说似乎是一个非常基本的问题,但由于我是新手,我不知道该怎么做。请帮帮我。 - Yogi
我建议你首先尝试适用于你的首选代码和情况。我对Android不熟悉。 - Priyank
嗨,我不是在问关于安卓的问题。我对安卓也是个新手。 - Yogi
抱歉,我指的是仅限于iPhone ;) - Priyank
1
我正在使用相同的代码,但仍然只收到前两个设备的通知,而不是所有设备[我正在向7个设备发送通知]。 - Raghbendra Nayak
显示剩余2条评论

2
我发现你需要为每个fwrite创建一个新的stream_context_create,以防止苹果因错误令牌而关闭连接。

发送每个通知后,您可以尝试简单地调用fread($socket):如果它返回FALSE,则重新创建套接字。您还可以将发送操作放在try&catch块中,并自动重新创建套接字并重新发送通知(可能会设置最大重试次数,以防万一)。 - user276648

1
这是我做的 这里
<?php 
        set_time_limit(0);
        $root_path = "add your root path here"; 
        require_once($root_path."webroot\cron\library\config.php");
        require_once($root_path."Vendor\ApnsPHP\Autoload.php");

            global $obj_basic;           
            // Basic settings

            $timezone = new DateTimeZone('America/New_York');
            $date = new DateTime();
            $date->setTimezone($timezone);
            $time =  $date->format('H:i:s');


            //Get notifications data to send push notifications
            $queueQuery = " SELECT `notifications`.*, `messages`.`mes_message`, `messages`.`user_id`, `messages`.`mes_originated_from`  FROM `notifications`
                                            INNER JOIN `messages`
                                            ON `notifications`.`message_id` = `messages`.`mes_id`

                                            WHERE `notifications`.`created` <= NOW()";

            $queueData = $obj_basic->get_query_data($queueQuery);

            if(!empty($queueData)) {

            // Put your private key's passphrase here:
            $passphrase = 'Push';

            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', 'server_certificates_bundle_sandbox.pem');
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

            // Open a connection to the APNS server
            $fp = stream_socket_client(
                'ssl://gateway.sandbox.push.apple.com:2195', $err,
                $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

            if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);

            echo '<br>'.date("Y-m-d H:i:s").' Connected to APNS' . PHP_EOL;

                foreach($queueData as $val) {
                        // Put your device token here (without spaces):
                        $deviceToken = $val['device_token'];

                        // Create message

                            // Get senders name
                            $sql = "SELECT `name` FROM `users` WHERE id =".$val['user_id'];
                            $name = $obj_basic->get_query_data($sql);
                            $name = $name[0]['name']; 
                            $message = $name." : ";

                            // Get total unread messaged for receiver
                            $query = "SELECT COUNT(*)  as count FROM `messages`  WHERE mes_parent = 0 AND user_id = ".$val['user_id']." AND mes_readstatus_doc != 0 AND mes_status = 1";
                            $totalUnread = $obj_basic->get_query_data($query);
                            $totalUnread = $totalUnread[0]['count']; 



                            $message .= " This is a test message.";


                        // Create the payload body
                        $body['aps'] = array(
                                'alert'         => $message,
                                'badge'     => $totalUnread,
                                'sound'     => 'default'
                         );

                        // Encode the payload as JSON
                        $payload = json_encode($body);

                        // Build the binary notification
                        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

                        // Send it to the server
                        $result = fwrite($fp, $msg, strlen($msg));

                        if (!$result) {
                            echo '<br>'.date("Y-m-d H:i:s").' Message not delivered' . PHP_EOL;  
                        } else {
                            $sqlDelete = "DELETE FROM `notifications` WHERE id = ".$val['id'];
                            $query_delete = $obj_basic->run_query($sqlDelete,'DELETE');

                            echo '<br>'.date("Y-m-d H:i:s").' Message successfully delivered' . PHP_EOL;
                        }
                }
                // Close the connection to the server
                fclose($fp);
                echo '<br>'.date("Y-m-d H:i:s").' Connection closed to APNS' . PHP_EOL;
            } else {
                echo '<br>'.date("Y-m-d H:i:s").' Queue is empty!';
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接