向所有用户发送推送通知

所以,我有一个应用程序。 这个应用程序,使用这个PHP代码发送推送通知:

<?php $deviceToken = '4bc9b8e71b9......235095a22d'; // Put your private key's passphrase here: $passphrase = '12345'; // Put your alert message here: $message = 'My Message Here!'; //////////////////////////////////////////////////////////////////////////////// $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.sandbox.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); 

我的问题是:如果我的应用程序中有多个用户,并且在terminal中运行此PHP代码,则推送通知将只发送到此设备(4bc9b8e71b9 …),或者它将被发送到我的用户? 如果这只会发送到这个设备,我怎么能发送推送给我所有的用户?

PS:我跟着这个教程,它的工作,除非因为我不知道是否推送将发送给我所有的用户。

对不起,英文不好, 谢谢

通常的做法是在数据库中存储令牌,一旦你需要发送令牌 – 只需从数据库中select令牌并循环。

代码可能看起来像这样

 $pdo = new PDO( "mysql:host=$db_host;port=$db_port;dbname=$db_name", $db_user, $db_pass ); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $select_tokens_sql = 'SELECT * FROM tokens'; $select_tokens_statement = $pdo->prepare($select_tokens_sql); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.sandbox.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); $select_tokens_statement->execute(); $tokens = $select_tokens_statement->fetchAll(); //loop through the tokens foreach($tokens as $token) { // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Message to the device ' . $token . ' not delivered' . PHP_EOL; else echo 'Message to the device ' . $token . ' successfully delivered' . PHP_EOL; } // Close the connection to the server fclose($fp); 

在完成发送推送通知之后,收听苹果反馈服务也可能是一个好主意。 它会告诉你,如果在某些设备上你的应用程序不再存在,所以你可以安全地从数据库中删除相应的令牌。

你将不得不循环所有的设备令牌,并用fwrite()把它们写入网关