・キーチェーンアクセスから 証明書を書き出す (例: pns.p12)
openssl pkcs12 -in pns.p12 -out pns.pem -nodes
をターミナルから実行してpemファイルを作成。
・デバイストークンをハードコーディングして、簡単にテストする場合 (PHP)
Apple Push Notification Services Tutorial: Part 1/2 – Ray Wenderlich にサンプルコードがある。
デバイスIDの調べ方は、
iOSのRemote Notificationを試してみた – daicham blog
あたりを参考にiOSのAppDelegate.mに実装する。
<?php // Put your device token here (without spaces): $deviceToken = '1ED5B1EB97B788EE359233F5A547E881E3FEE0E2DED7A0AEB258ACD11050E051'; // Put your private key's passphrase here: $passphrase = ''; // Put your alert message here: $message = 'My first push notification!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'pns.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);
をローカルに保存して (simplepush.php)
php simplepush.php
で実行する。
Connected to APNS Message successfully delivered
と表示され、すぐ通知が飛んでくる。
(エミュレーターは非対応なので、検証出来るのは実機のみ、アプリを起動中は通知が来ないので注意)
Rubyの場合はこれを使うと良さそう。
jpoz/APNS · GitHub