增加服务器端的徽章编号

时间:2014-07-01 15:29:03

标签: php ios push-notification

我有一张这样的表

|------------|-----------|
|device_token|badge_count|
|------------|-----------|
|123456789   |3          |
|------------|-----------|
|987654321   |2          |
|------------|-----------|

我有php创建两个数组:

$query = mysql_query("SELECT * FROM push");
$deviceToken = array();
while($row = mysql_fetch_assoc($query)){
    $deviceToken[] = $row['device_token'];
    $badgeCount[] = $row['badge_count'];
}
然后我按照这样插入它们:

foreach($deviceToken as $key=>$value){
        echo $badgeCount[$key];

        $body['aps'] = array(
            'alert' => $message,
            'sound' => 'default',
            'badge' => $badgeCount[$key],
        );

        $payload = json_encode($body);

        $msg = chr(0) . pack('n', 32) . pack('H*', $value) . pack('n', strlen($payload)) . $payload;
        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result){
            die( 'Message not delivered' . PHP_EOL);
        }
}

这会返回回显3 2。但$payload未能成功提供正确的"徽章编号"

并且在推送通知中没有显示徽章编号。如果我将'badge' => $badgeCount[$key]替换为'badge' => 2,则徽章编号显示为2?

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:2)

返回关联数组:

$query = mysql_query("SELECT device_token, badge_count FROM push");
$devices = array();
while($row = mysql_fetch_assoc($query)){
    $devices[] = $row;
}

循环播放设备:

foreach($devices as $device){

        $body['aps'] = array(
            'alert' => $message,
            'sound' => 'default',
            'badge' => (int)$device['badge_count'],//very important cast !!!
        );

        $payload = json_encode($body);

        $msg = chr(0) . pack('n', 32) . pack('H*', $device['device_token']) 
                      . pack('n', strlen($payload)) . $payload;

        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result){
            die( 'Message not delivered' . PHP_EOL);
        }
}