iOS推送通知在服务器上运行时有效,但在实际设备上不起作用



我正在使用php为iOS开发远程推送通知。当我使用命令php push_notification.php(push_notification.php是我的api的文件名(从服务器运行代码时,它成功地发送了通知。但是,当我尝试从post-man或真实设备运行api时,它不会发送任何通知,并给我一个错误,说Failed to connect to the APNS server. Error no = 0<br/>。这是我的密码。

<?php
/* sample device token*/
$id = '9A057567E5208D4471294A0FDFFF777EEE92E2205EBA9334C5ADE5A383F7B344';
$apnsServer = 'ssl://gateway.push.apple.com:2195';
/* Make sure this is set to the password that you set for your private key
when you exported it to the .pem file using openssl on your OS X */
$privateKeyPassword = 'password';
$message = 'Welcome to iOS 10 Push Notifications';
/* Pur your device token here */
$deviceToken = $id;
/* Replace this with the name of the file that you have placed by your PHP
script file, containing your private key and certificate that you generated
earlier */
$pushCertAndKeyPemFile = dirname(__FILE__).'/PushCertificateAndKey.cer';
$stream = stream_context_create();
stream_context_set_option($stream,
'ssl',
'passphrase',
$privateKeyPassword);
stream_context_set_option($stream,
'ssl',
'local_cert',
$pushCertAndKeyPemFile);
stream_context_set_option( $stream , 'ssl', 'verify_peer', false);
$connectionTimeout = 60;
$connectionType = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
$connection = stream_socket_client($apnsServer,$errorNumber,$errorString, $connectionTimeout, $connectionType,$stream);
if (!$connection){
echo "Failed to connect to the APNS server. Error no = $errorNumber<br/>";
exit;
} else {
echo "Successfully connected to the APNS. Processing...</br>";
}
$messageBody['aps'] = array('alert' => $message,
'sound' => 'default',
'badge' => 2,
);
$payload = json_encode($messageBody);
$notification = chr(0) .
pack('n', 32) .
pack('H*', $deviceToken) .
pack('n', strlen($payload)) .
$payload;
$wroteSuccessfully = fwrite($connection, $notification, strlen($notification));
if (!$wroteSuccessfully){
echo "Could not send the message<br/>";
}
else {
echo "Successfully sent the message: ".$message."to device token: ".$id.PHP_EOL;
}
fclose($connection);
?>

我知道推送通知有很多问题。但我认为我的不同之处在于,我可以从服务器发送通知,但不能从设备或邮递员发送通知。这有什么问题,为什么当我从服务器上运行它而不是在真正的设备上运行时它能工作?

为了正确测试Push Notifications流,您需要检查一些事情。

  • 您是否在服务器上使用DevelopmentProduction证书发送Push Notifications
  • 您是直接从Xcode安装应用程序,还是使用Development (Debug)Production (Release)版本
  • 还要确保您已经在开发机器上安装了以.p12格式安装的APNS证书

您必须注意,从开发版本安装的应用程序只能接收来自具有开发证书的服务器的通知
而生产应用程序只能接收来自具有生产证书的服务器的通知。

希望这能帮助

最新更新