views:

430

answers:

2

Hi Guys,

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);
}?>

What am I doing wrong?

Thx in advance, Mladjo

A: 

Taking a shot in the dark here. Looking at your for loop.

It looks like you open the connection and push the message... but does that connection close itself? Do you need to initiate a new connection for each push thereby making it necessary to close the first connection at the end of the while loop before re-initiating another?

Structure
+1  A: 

Hi Mladen,

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);
}?>

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.

Yannooo
Mladen
Have you tried build your messages with this code:$apns_message = chr(0).pack('n', 32).pack('H*', $device_token).pack('n', strlen($payload)).$payload;Also, are you sending all this push notifications to the same device? if so then only one will appear on the device.
Yannooo
My messages are built with that code. I am sending them all to the same iPod touch. With this loop, I am receiving 2 instead of 5. Even when I try with different tokens, it only sends to the first one.
Mladen
Maybe you should try to flush the socket by closing it properly at the end of your script fclose($apns);
Yannooo