douhan8610 2019-02-13 05:02
浏览 144
已采纳

如何以及从服务器向APN发送什么以便APN将通知发送给设备?

I am an iOS developer and i was asked to what type(whole i.e header as well as body) of request to hit APN to get notification to device.

I read many tutorial for setup of server for APN but I am unable to understand as i have no knowledge about PhP and Node Js. After reading apple document , I came to know that it uses http/2 and other various tag and value. But i am unable to construct full request. Any help is highly appreciated.

  • 写回答

2条回答 默认 最新

  • dongyuxin5353 2019-02-13 05:25
    关注

    To send an APNs request using PHP, you need these requirements:

    1. A .pem certificate which should exist in the same path of your php script.
    2. The Device Token, which is needed to send the notification to a specific device.

    Then you can try the following code:

    <?php
        $apnsServer = 'ssl://gateway.push.apple.com:2195';
        $privateKeyPassword = '1234'; // your .pem private key password
    
        $message = 'Hello world!';
    
        $deviceToken = 'YOUR_DEVICE_TOKEN_HERE';
    
        $pushCertAndKeyPemFile = 'PushCertificateAndKey.pem'; // Your .pem certificate
        $stream = stream_context_create();
        stream_context_set_option($stream,
        'ssl',
        'passphrase',
        $privateKeyPassword);
        stream_context_set_option($stream,
        'ssl',
        'local_cert',
        $pushCertAndKeyPemFile);
    
        $connectionTimeout = 20;
        $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...";
        }
        $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.";
        }
        else {
        echo "Successfully sent the message.";
        }
        fclose($connection);
    
    ?>
    

    Refer to this link for more details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果