Batch / multiple iOS Push Notification code - work

2019-05-15 04:26发布

问题:

The following code works fine if the number of devices I send to is 2 - i.e., they both receive the push notifications. But if I raise that limit to 100, no push notifications are received.

I have read up on this and it looks like I am sending the batch notifications correctly (i.e., multiple requests via a single connection); the timeout of the connection is set nice and high (60 seconds); the output of the code all looks in order; nothing in the apache error log, so I don't see where the problem is.

My customer's getting really hacked off. Can anyone help??

function sendIosPushes() {

$payload['aps'] = array('alert' => pushMessage, 'badge' => badgeNumber, 'sound' => 'default');
$payload = json_encode($payload);

//$statement = "SELECT * FROM push_ios WHERE device_token = 'device token of my iphone" OR device_token = 'device token of my ipod'; //works selecting my two devices from table
$statement = "SELECT * FROM push_ios"; //doesn't work when selecting all devices from table


$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', apnsCert);

$connectTimeout = 60;
$apns = stream_socket_client('ssl://' . apnsHost . ':' . apnsPort, $error, $errorString, $connectTimeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);

$numDevices = 0;
$numRequestsSent = 0;
$result = mysql_query($statement);
while ($row = mysql_fetch_assoc($result)) {
    $numDevices++;
    try {
        $deviceToken = $row['device_token'];

        //$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', $deviceToken) . chr(0) . chr(strlen($payload)) . $payload;
        $apnsMessage = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; //from http://stackoverflow.com/questions/1642411/sending-multiple-iphone-notifications

        $fwriteRes = fwrite($apns, $apnsMessage, strlen($apnsMessage));
        echo "Push sent to " . $deviceToken . "<br />\n";

        $numRequestsSent++;
    }
    catch(Exception $e) {
        echo "1. Exception: " . $e->getMessage() . "<br />\n";
    }
}

fclose($apns);


if ($error != 0 || (isset($errorString) && strlen($errorString) > 0 )) {
    echo "ERROR: " . $error . " - ". $errorString . "<br />\n";
}

return $numDevices . " iOS devices. " . $numRequestsSent . " requests sent.";

}

回答1:

You probably have some invalid device tokens in your DB.

In case of an invalid device token, Apple will return an error response if you use the newer binary format (in which you send a message id and message expiry), which you don't. In your case an invalid token will simply close the socket, but you'll have no way to know which message caused the problem.

You should read about error checking here. You should read about the format here.