使用PHP向所有iOS应用程序用户发送推送通知

时间:2014-05-29 14:56:20

标签: php ios push-notification apple-push-notifications

我使用这个PHP向我的应用的一个用户发送推送通知。一切都很好用,但我需要将它发送给所有用户:

$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);

如何更改此内容以将其发送给所有用户?

1 个答案:

答案 0 :(得分:1)

for ($deviceToken in $allDevices) {
    SendPushToDevice($deviceToken);
}

请注意!如果计算$ allDevices> 100,那么你必须在一定的时间间隔内完成它,否则推送不会发送。

for ($i = 0; $i < count($allDevices); $i++) {
    if ($i > 0 && $i % 100 == 0) {
        // your sleep function
    } else {
        $deviceToken = $allDevices[$i];
        SendPushToDevice($deviceToken);
    }
}