LoginSignup
6
6

More than 5 years have passed since last update.

Corona SDK + Parse.com でプッシュ通知をする

Last updated at Posted at 2013-12-02

Corona SDK と Parse.com にてプッシュ通知を試してみました。
超ざっくりですが、まとめてみます。

ライブラリがサポートされていない

まず、最初に残念なお知らせになりますが、Corona SDK 用のライブラリがサポートされていません。つまり、ライブラリを突っ込んで require して数行追加するだけで簡単プッシュ通知!とはなりません、残念ながら。

一応、サードパーティのライブラリはあるようですが、更新が 2011 年で停止しているため、信頼性に欠けるので利用するかどうかはよく考えた方が良さそうです。

API は用意されている

ライブラリはサポートされていませんが、API は用意されています。これを利用しましょう。

サンプルコード

以下のリポジトリに全体のサンプルコードがあります。

設定ファイルに notification の項目を記述しておきます。

config.lua
application = {
  content = {
    width = 320,
    height = 480,
    scale = "letterBox",
    fps = 30,
  },

  notification = {
    iphone = {
      types = {
        "badge", "sound", "alert"
      },
    },
  },
}

Parse にて提供される Application IDREST API Key を利用して、API を発行します。

main.lua
local applicationId = "xxxxx"
local restApiKey    = "xxxxx"

require("parse")

parse.initialize(applicationId, restApiKey)

local function listener(event)
  if event.isError then
    print("Error")
  elseif event.status == "began" then
    print("Began")
  elseif event.status == "installations" then
    print("Installations")
  elseif event.status == "ended" then
    print("Ended")
  end
end
parse.installations(listener)

Parse ロジックを parse.lua に閉じ込めてライブラリ化しました。ここでは、iOS 限定のロジックにしています。

parse.lua
module(..., package.seeall)

function initialize(applicationId, restApiKey)
  params = {
    headers = {
      ["X-Parse-Application-Id"] = applicationId,
      ["X-Parse-REST-API-Key"]   = restApiKey,
      ["Content-Type"]           = "application/json",
    },
  }
end

function updateListenerStatus(status)
  if listener then
    listener{ status = status }
  end
end

function installations(listener)
  local json = require("json")

  local function notificationListener(event)
    if event.type == "remoteRegistration" then
      params.body = json.encode({
        deviceType = "ios",
        deviceToken = event.token,
      })

      local function networkListener(event)
        if event.isError then
          if listener then listener{ isError = event.isError, status = "ended" } end
        else
          if listener then listener{ status = "ended" } end
        end
      end

      network.request("https://api.parse.com/1/installations", "POST", networkListener, params)
      if listener then listener{ status = "installations" } end
    end
  end

  Runtime:addEventListener("notification", notificationListener)
  if listener then listener{ status = "began" } end
end

実機で動作確認をすると、プッシュ通知を受け取るか否かを選択するアラートが表示されます。許可した場合、Parse 側にデバイス情報が登録されて、以後、Parse 側からプッシュ通知をすることが可能になります。

追記 2014/02/13(木)

手軽に使えそうな Corona SDK + Parse.com なモジュールが公開されているようです。

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