I'm using this PHP to send out push notifications to just one user of my app. Everything works great with that, but I need to send it to all users:
$deviceToken = 'DeviceTokenHere';
// Put your private key's passphrase here:
$passphrase = 'Passphrase Here';
// Put your alert message here:
$message = 'There are 2 new requests at the bottom of the list. Please check them out.';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.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 APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'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 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
How would I alter this to send it to all users?
for ($deviceToken in $allDevices) {
SendPushToDevice($deviceToken);
}
Note! If count of $allDevices > 100, then you must do it with some time intervals, otherwise push will not delivered.
for ($i = 0; $i < count($allDevices); $i++) {
if ($i > 0 && $i % 100 == 0) {
// your sleep function
} else {
$deviceToken = $allDevices[$i];
SendPushToDevice($deviceToken);
}
}