2012年5月2日水曜日

APNs:デバイストークンを受け取る

Apple Push Notification Service を今回実装したのでそれのメモです。
iPhoneのアプリ内でalertの様に出るお知らせです。

まずは送る相手をDBに保存するためにデバイストークンを保存します。
マイグレーションの作成です。

~_create_device_tokens.rb
class CreateDeviceTokens < ActiveRecord::Migration
  def up
    create_table :device_tokens do |t|
      t.timestamps
    end
    ActiveRecord::Base.connection.execute(
      "ALTER TABLE device_tokens ADD token VARBINARY(32) NOT NULL;")
  end

  def down
    drop_table :device_tokens
  end
end
device_tokensという名前にしました。

次にルーティングです。端末側へ情報を出すものは全て「namespace」で分けた
「api」に指定します。
routes.rbに以下を追加します。
if Rails.env.development?
   resources :device_tokens, :only => [ :new, :create ]
else
   resources :device_tokens, :only => [ :create ]
end
開発と本番で分けました。
あとはアプリ側からこちらに向けたデバイストークンを拾うだけです。

api/device_tokens_controller.rbを作成します。
class Api::DeviceTokensController < ApplicationController
  protect_from_forgery :except => :create

  def create
    @dt = DeviceToken.find_or_new(params[:token])
    if @dt.save
      render :text => "OK", :content_type => "text/plain"
    else
      render :text => "NG", :content_type => "text/plain",
        :status => 400
    end
  end
end
そして最後にモデルです。
device_token.rbを作成します。
class DeviceToken < ActiveRecord::Base
  validates :token, :presence => true, :length => { :is => 32 }

  class << self
    def find_or_new(token)
      token.force_encoding("ascii-8bit") if RUBY_VERSION.to_f >= 1.9
      dt = find_by_token(token) || new(:token => token)
      dt.updated_at = Time.current
      dt
    end
  end
end
Rubyのバージョンを1.9の時は「force_encoding」を「ascii-8bit」としています。
以上で「post /api/device_tokens?token=〜」というURLで取得できます。

0 件のコメント:

コメントを投稿