6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでParse.com使ってpush通知を送る

Last updated at Posted at 2015-10-19

mBaaSのParse.comを利用してiOSスマホアプリを制作しています。
サーバーサイドをrailsで用意し、push通知を送るのにParse REST APIの機能を使います。

環境

rails 4.2.3
parse-ruby-client 0.3.0

Parse API公式ドキュメント

parseに登録

※概要だけ。(スイマセン。。)

Parseにアプリを登録して、Settings→Keysより、Application IDREST API Keyを取得します。
↓ではdotenvを利用してPARSE_APP_IDPARSE_API_KEYとして登録しています。

Gemfile

ParseのAPIを使うのにサードパーティ製のSDK gemがあったのでそれを使います。

  gem 'parse-ruby-client'

push通知用クラスを作った

parse-ruby-clientのドキュメントに沿って作っただけです。(pushだけでなく他もいろいろ使えそう!)

parse_service.rb
class ParseService
  PUSH_TYPE_ALL = 0
  PUSH_TYPE_PERSONAL = 1
  PUSH_TYPE_RSPEC = 2

  def initialize
    Parse.init(application_id: ENV['PARSE_APP_ID'], api_key: ENV['PARSE_API_KEY'])
  end

  def request_push_notification(message, value, push_type, device_token = nil)
    data = { alert: message }.merge(value)
    push = Parse::Push.new(data)

    case push_type
    when PUSH_TYPE_ALL
      push.where = {}
    when PUSH_TYPE_PERSONAL
      return false if device_token.blank?
      push.where = { deviceToken: device_token }
    when PUSH_TYPE_RSPEC
      return true
    else
      return false
    end
    push.save
  end
end

push通知するときはこんな感じ

※個別pushの場合。

push_notification.rb
  def self.request_parse_push_notification
    parse = ParseService.new
    push_result = parse.request_push_notification(
      'こんにちは!',
      {badge: '1', sound: 'bingbong.aiff', activity_badge: '1'},
      ParseService::PUSH_TYPE_PERSONAL,
      'device_id',
  end

device_idは前もってクライアントアプリからサーバーに送ってもらう必要あります。

jsonのとこには好きなように情報を入れられるので、例えば通知後のアプリの挙動を指定できたりします。(そのへんは設計次第で自由自在)
また、parseのサイトで送信状況は確認できるので、そこらへんを見つつデバッグすると良い感じです。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?