LoginSignup
16
13

More than 5 years have passed since last update.

Ruby(Grocer)でiOSアプリにプッシュ通知を送る

Last updated at Posted at 2015-06-11

開発中のアプリに自分のローカルからプッシュ通知を送りたい。

APNSを利用するためのGemをいくつか調べたのですが、Grocerを使って簡単にプッシュ通知を送ることができました。

基本的な使い方はGitHubのドキュメントに従えばOKです。
https://github.com/grocer/grocer

1. Grocerをインストール

Grocerのgemをインストールします。

$ sudo gem install grocer

2. cert.pemを作成

プッシュ送出側が保持する証明書を、通例サーバサイドに格納する.p12から.pem形式に変換する必要があります。

$ openssl pkcs12 -in exported_certificate.p12 -out cert.pem -nodes -clcerts -des3

入力すると2回パスワード入力を求められます。

Enter Import Password:

-> 何も入力しなくてOKです。

Enter PEM pass phrase:

-> 後述のコードの passphrase に入力するパスワードになります。

3. プッシュ通知を送るためのコード

push.rb
require 'grocer'

pusher = Grocer.pusher(
  certificate: "./cert.pem",      # required
  passphrase:  "<パスフレーズ>",                       # optional
  gateway:     "gateway.sandbox.push.apple.com", # optional
  port:        2195,                     # optional
  retries:     3                         # optional
)

notification = Grocer::Notification.new(
  device_token:      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  alert:             "Hello from Grocer!",
  badge:             42,
  category:          "a category",         # optional; used for custom notification actions
  sound:             "siren.aiff",         # optional
  expiry:            Time.now + 60*60,     # optional; 0 is default, meaning the message is not stored
  identifier:        1234,                 # optional; must be an integer
  content_available: true                  # optional; any truthy value will set 'content-available' to 1
)

pusher.push(notification) # プッシュを送出

4. push.rbを実行

$ ruby push.rb

設定に関して気をつけるポイント

サーバの設定

certificate

push.rbからpemファイルの相対パスを指定します。
今回のサンプルコードの場合、同じディレクトリに格納すればよいです。

passphrase

pemファイルを生成した時に入力したパスフレーズを入力します。

gateway

Development の場合

gateway.sandbox.push.apple.com

Production の場合

gateway.push.apple.com

通知の設定

device_token

APNSから取得できるデバイストークンを「半角スペース、<>」なしで指定

content-available

trueにすることで、バックグラウンドでの処理を有効化します。

16
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13