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条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备