如何通过PHP将推送通知发送到多个IOS设备?

时间:2018-12-26 08:41:05

标签: php ios push-notification

我的model.php文件中包含以下示例代码。如果我将多个设备令牌硬编码到我的代码中,一切都将正常工作。但是,当我尝试发送动态设备令牌时,它不起作用。我该如何解决这个问题?请帮忙。

//Get device token
$sql = "SELECT DISTINCT device_token FROM apns_devices";
$deviceToken_array = ARRAY();

 while ($row = mysql_fetch_assoc($sql))
            $deviceToken_array[] = $row;
            //THIS CODE DOES NOT WORK

        //=====================================================================
    //IF I USE THIS CODE< IT WILL WORK CORRECTLY.
    // $deviceToken_array = [  '19c5040d8f1adf2741fbf2520458d8326cc0ebedb715a00081b4c49e765d4c3d', '19c5040d8f1adf2741fbf2520458d8326cc0ebedb715a00081b4c49e765d4c3d','19c5040d8f1adf2741fbf2520458d8326cc0ebedb715a00081b4c49e765d4c3d'  ];
             //=====================================================================
    //Build Content of Notification
    $body['aps'] = array(
                                'alert' => array(
                                'title' => $data['title'],
                                'body' => $data['description'],
                                'badge' => 1
                               ),
                                'sound' => 'default'
                               );

    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', '/XXX/admin/XXXDevPushNotification.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', 'XXX');
         //Build Socket Connection
    $fp = stream_socket_client("ssl://gateway.sandbox.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    if (!$fp)
    {
      print "Failed to connect $err $errstrn";
      return;
    }

    print "Connection OK";

    foreach($deviceToken_array as $deviceToken) {
       // Encode the payload as JSON
       $payload = json_encode($body);
       echo $payload;
       // 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));
       echo $result;
       if (!$result)
       echo 'Message not delivered' . PHP_EOL;
       else
       echo 'Message successfully delivered' . PHP_EOL;
    }
        fclose($fp);

1 个答案:

答案 0 :(得分:0)

最后,我找到了如下解决方案:-

 $sql = "SELECT DISTINCT device_token FROM apns_devices";

                         $result = $this->db->query($sql);
                         $records = $result->result_array();
                         $deviceToken_array = ARRAY();

                         foreach($records as $deviceToken) {
                         $result = $deviceToken['device_token'];
                         array_push($deviceToken_array, $result);
                         }