Reputation: 5330
I'm trying to send notifications for multiple devices. So I get tokens to an array, open connection, send notifications in a loop, close connection.
However, After 9-10 devices, it stops sending. I believe Apple somehow drops the connection .
Here's my code:
$message = 'Push';
$passphrase = 'mypass';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyPemFile.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.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 'Connected to Apple service. ' . PHP_EOL;
// Encode the payload as JSON
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
$payload = json_encode($body);
$result = 'Start'.PHP_EOL;
$tokenArray = array('mytoken');
foreach ($tokenArray as $item)
{
// Build the binary notification
$msg = chr(0).pack('n', 32).pack('H*', $item).pack('n', strlen($payload)).$payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Failed message'.PHP_EOL;
else
echo 'Successful message'.PHP_EOL;
}
// Close the connection to the server
fclose($fp);
Is there something wrong with my code? I think I need to open connection once, send notifications then close. Should I be doing fwrite() with multiple tokens? I don't know how though. Any ideas or solutions are accepted.
By the way the answer is like:
Successful message
Successful message
Successful message
Successful message
Successful message
Successful message
Successful message
Successful message
Successful message
Successful message
Failed message
Failed message
Failed message
Failed message
Failed message
...
Failed message
P.S. I had character issue with same code but it is solved in another question, this is another problem, not a duplicate.
Upvotes: 1
Views: 5710
Reputation: 5544
The first failed message likely has something wrong with it, at which point Apple will close the connection to signal to you that there was an issue. If you're using the enhanced format, you have an opportunity to get some feedback before Apple closes the connection to see what was wrong with the notification you sent. After this happens you must re-establish a connection to send more messages.
There are a number of reasons it might fail. You might have sent an invalid device token, your payload might be invalid or of the wrong length, etc.
Best check out the documentation for APNS: http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html
Upvotes: 1