ios 和 android 将通知推送到多个设备
ios and android push notifications to multiple devices
我真的很纠结这个。这段代码不是我创建的,但我已经对其进行了更改,因此它可以正常工作。我的目标是让它能够向所有使用该应用程序的设备发送推送通知。我是一个 ios 和安卓编程的人,所以我会尽力而为。我已经清理并更改了给我的代码,这样它现在只会向一台设备发送通知。
这是代码
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
include 'notifications.php';
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
} else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
}
}
$url = 'https://android.googleapis.com/gcm/send';
$fields = array( 'registration_ids' => $regis, 'data' => array( 'message'=>$message,'count'=>1 ) );
$headers = array(
'Authorization: key=AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode ( $fields ) );
$result = curl_exec( $ch );
curl_close ( $ch );
//Apple Push notification
// This this a fake device id:
$deviceToken = "5d8b3165fc03645d23c2651badd69f07d028aee801acf1d25a4d230882156755";
// fake password:
$passphrase = '123456789';
$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',
'badge' => '1'
);
// 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);
}
include 'index.php';
?>
我将 ios 设备令牌添加到 $deviceToken,将 android 设备令牌添加到 $regi,它将发送到手机。我唯一改变的部分是 Apple 推送通知部分不起作用。在我更改它之前,苹果推送通知使用的是 $dev 变量,而 android 使用的是 $regi。现在我知道设备令牌在应用程序启动时被发送到服务器,所以我猜测它们没有存储在变量中。有没有你能看到的问题,我怎样才能把它们打印出来看看它们是否为空?
谢谢
我不久前就明白了这一点,但我会与其他正在苦苦挣扎的人分享。
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
include 'notifications.php';
}
else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
}
else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
}
}
$deviceToken=$_REQUEST['device'];
$json=json_decode($deviceToken);
//google Push notification
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg' );
//build the message
$fields = array
(
'registration_ids' => $regis,
'data' => array( 'message'=> $message,'count'=>1 )
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
//Apple Push notification
// Certificate password:
$passphrase = '123456789';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckStudioeast.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);
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => '1'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Loop though device tokens
foreach($ios as $dev) {
if($dev!=''){
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $dev) . pack('n', strlen($payload)) . $payload;
//Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
echo 'Message not delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
include 'index.php';
}
?>
问题似乎是应用程序正在向数据库发送开发设备令牌,因此我将 xcode 中的 didRegisterForRemoteNotificationsWithDeviceToken 函数更新为:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
#ifdef DEBUG
// Update the database with our development device token
NSLog(@"IN DEVELOPMENT MODE!!!!!!!");
#else
// Update the database with our production device token
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"content---%@", token);
kSetValueForKey(@"device_token", token);
[self updateDeviceToken:token];
#endif
}
我还发现,如果用户拒绝允许推送通知的请求,它会向我的数据库发送一个 0 的设备令牌,如果使用它会停止发送通知。所以我在我的 php 文件中对我的设备令牌进行排序的地方我添加了更多逻辑来忽略所有只有 0.
的令牌
在将其添加到我的 $ios 数组之前,我只是简单地检查了长度是否超过 25 个字符,而之前我没有
旧代码:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
新代码:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
我发现的一个主要问题是,如果您向苹果生产推送通知服务器发送的设备令牌不是有效的生产设备令牌,它就不会向任何设备发送通知。这就是为什么我没有工作,我在我的 php 代码和 Objective-c 代码中添加了额外的逻辑来过滤掉所有无效的设备令牌。
希望这对人们有所帮助。
while ($row = mysql_fetch_array($result1)) //fetch datafrom loop
{
$dev = $row["device_token"]; // your devide token
if( strlen ( $dev ) > 65 ) { // for android
$regis[] = $row['device_token'];
}
else
{
$ios[] = $row['device_token']; // for ios
}
}
foreach($regis as $dev1) {
$id=$dev1;
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'notification' => array (
"body" => $mess,
"icon" =>"icon",
"sound"=> ""
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "---your key---",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
}
foreach($ios as $dev) {
if($dev!='')
{
$deviceToken=$dev;
$passphrase = '';
// Put your alert message here:
$message = $mess;
$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);
// Create the payload body
$body['aps'] = array(
'alert' => array(
'body' => $message,
),
'badge' => +1,
'sound' => 'default',
'content-available' => '1',
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
{
?>
<script>
alert("Push notification is successfully sent");
</script>
<?php
}
else
{
?>
<script>
alert("Mesaage is successfully sent");
</script>
<?php
}
curl_close ( $ch );
fclose($fp);
}
我真的很纠结这个。这段代码不是我创建的,但我已经对其进行了更改,因此它可以正常工作。我的目标是让它能够向所有使用该应用程序的设备发送推送通知。我是一个 ios 和安卓编程的人,所以我会尽力而为。我已经清理并更改了给我的代码,这样它现在只会向一台设备发送通知。
这是代码
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
include 'notifications.php';
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
} else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
}
}
$url = 'https://android.googleapis.com/gcm/send';
$fields = array( 'registration_ids' => $regis, 'data' => array( 'message'=>$message,'count'=>1 ) );
$headers = array(
'Authorization: key=AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode ( $fields ) );
$result = curl_exec( $ch );
curl_close ( $ch );
//Apple Push notification
// This this a fake device id:
$deviceToken = "5d8b3165fc03645d23c2651badd69f07d028aee801acf1d25a4d230882156755";
// fake password:
$passphrase = '123456789';
$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',
'badge' => '1'
);
// 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);
}
include 'index.php';
?>
我将 ios 设备令牌添加到 $deviceToken,将 android 设备令牌添加到 $regi,它将发送到手机。我唯一改变的部分是 Apple 推送通知部分不起作用。在我更改它之前,苹果推送通知使用的是 $dev 变量,而 android 使用的是 $regi。现在我知道设备令牌在应用程序启动时被发送到服务器,所以我猜测它们没有存储在变量中。有没有你能看到的问题,我怎样才能把它们打印出来看看它们是否为空?
谢谢
我不久前就明白了这一点,但我会与其他正在苦苦挣扎的人分享。
<?php
include 'conn.php';
if ( $_REQUEST['key'] == 'notification' ) {
$message = $_REQUEST['text'];
$text = mysql_real_escape_string( $_REQUEST['text'] );
$start = $_REQUEST['start'];
$end = $_REQUEST['end'];
$date = date( "Ymd", strtotime( $_REQUEST['date'] ) );
$callus = $_REQUEST['callus'];
$in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');";
mysql_query($in);
include 'notifications.php';
}
else {
$message = mysql_real_escape_string( $_REQUEST['text'] );
$time = date( 'Y-m-d H:i:s' );
$in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');";
mysql_query( $in );
$sel="SELECT * FROM `users` GROUP by device_token";
$rs = mysql_query( $sel ) or die('');
if ( mysql_num_rows( $rs ) != 0 ) {
while( $row=mysql_fetch_array( $rs ) ) {
$regi = array();
$regi[] = $row['device_token'];
$dev = $row['device_token'];
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
}
else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
}
}
$deviceToken=$_REQUEST['device'];
$json=json_decode($deviceToken);
//google Push notification
// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg' );
//build the message
$fields = array
(
'registration_ids' => $regis,
'data' => array( 'message'=> $message,'count'=>1 )
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
//Apple Push notification
// Certificate password:
$passphrase = '123456789';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckStudioeast.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);
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => '1'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Loop though device tokens
foreach($ios as $dev) {
if($dev!=''){
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $dev) . pack('n', strlen($payload)) . $payload;
//Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
echo 'Message not delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
include 'index.php';
}
?>
问题似乎是应用程序正在向数据库发送开发设备令牌,因此我将 xcode 中的 didRegisterForRemoteNotificationsWithDeviceToken 函数更新为:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
#ifdef DEBUG
// Update the database with our development device token
NSLog(@"IN DEVELOPMENT MODE!!!!!!!");
#else
// Update the database with our production device token
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"content---%@", token);
kSetValueForKey(@"device_token", token);
[self updateDeviceToken:token];
#endif
}
我还发现,如果用户拒绝允许推送通知的请求,它会向我的数据库发送一个 0 的设备令牌,如果使用它会停止发送通知。所以我在我的 php 文件中对我的设备令牌进行排序的地方我添加了更多逻辑来忽略所有只有 0.
的令牌在将其添加到我的 $ios 数组之前,我只是简单地检查了长度是否超过 25 个字符,而之前我没有
旧代码:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else {
$ios[] = $dev;
}
新代码:
if( strlen ( $dev ) > 65 ) {
$regis[] = $row['device_token'];
} else if ( strlen ($dev) > 25 ) {
$ios[] = $dev;
}
我发现的一个主要问题是,如果您向苹果生产推送通知服务器发送的设备令牌不是有效的生产设备令牌,它就不会向任何设备发送通知。这就是为什么我没有工作,我在我的 php 代码和 Objective-c 代码中添加了额外的逻辑来过滤掉所有无效的设备令牌。
希望这对人们有所帮助。
while ($row = mysql_fetch_array($result1)) //fetch datafrom loop
{
$dev = $row["device_token"]; // your devide token
if( strlen ( $dev ) > 65 ) { // for android
$regis[] = $row['device_token'];
}
else
{
$ios[] = $row['device_token']; // for ios
}
}
foreach($regis as $dev1) {
$id=$dev1;
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'notification' => array (
"body" => $mess,
"icon" =>"icon",
"sound"=> ""
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "---your key---",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
}
foreach($ios as $dev) {
if($dev!='')
{
$deviceToken=$dev;
$passphrase = '';
// Put your alert message here:
$message = $mess;
$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);
// Create the payload body
$body['aps'] = array(
'alert' => array(
'body' => $message,
),
'badge' => +1,
'sound' => 'default',
'content-available' => '1',
);
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
}
}
if (!$result)
{
?>
<script>
alert("Push notification is successfully sent");
</script>
<?php
}
else
{
?>
<script>
alert("Mesaage is successfully sent");
</script>
<?php
}
curl_close ( $ch );
fclose($fp);
}