发送多个 iPhone 通知 [英] Sending multiple iPhone notifications
问题描述
当我需要发送一个通知时,我的代码工作正常,但是每次我需要发送多个通知时,它只发送第一个.代码如下:
My code works ok when I need to send one notification, but each time when I need to send more than one, it only sends the first one. Here is the code:
<?php
$device_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$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);
for($i=0; $i<5; $i++)
{
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
}?>
我做错了什么?
提前谢谢,姆拉乔
推荐答案
您应该只打开与 apns 的连接一次.现在你正在循环中打开它,这是错误的.我也在使用稍微不同的方案来构建我的消息.你应该这样做:
You should open the connection to apns only once. Right now you are opening it in the loop which is wrong. I'm also using a slightly different scheme to build my messages. You should instead do it in this way:
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
for($i=0; $i<5; $i++)
{
$apns_message = chr(0).pack('n', 32).pack('H*', $device_token).pack('n', strlen($payload)).$payload;
fwrite($apns, $apnsMessage);
}?>
另请注意,Apple 建议使用相同的连接来发送所有推送通知,因此您不应在每次有推送通知要发送时都连接.
Also note that apple recommends using the same connection to send all your push notifications so you shouldn't connect every time you have a push notification to send.
这篇关于发送多个 iPhone 通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!