7
3

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.

AWS SNSで複数プラットフォーム上のアプリへのメッセージを送るときにはJSON文字列を渡さないといけない

Posted at

メッセージでのカスタムプラットフォーム固有のペイロードのモバイルデバイスへの送信 - Amazon Simple Notification Serviceにて書かれていることをaws-sdk | RubyGems.orgで試してみる。

送信するメッセージは以下の通り

{ 
  "default": "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.",
  "APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\":\"www.amazon.com\"} }",
  "GCM":"{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"
}

よく見ると、APNSGCMのキーに対してはJSONの文字列が入っている。
この部分を以下のようにしてしまうと通知を受け取るアプリは期待する値が入らず、defaultキーの値が単純に送られてしまう。

{ 
  "default": "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.",     
  "APNS": {
    "aps": {
      "alert": "Check out these awesome deals!",
      "url": "www.amazon.com"
    }
  },
  "GCM": {
    "data": {
      "message": "Check out these awesome deals!",
      "url": "www.amazon.com"
    }
  },
}

複数プラットフォーム上に通知を送る際には通知を行うプラットフォームをキーに値にはJSONの文字列を渡す。

通知を行うプラットフォーム毎にメソッドを分けた方がすっきりするような感じがして以下のようなコードを書いた。


def apns(message, url)
  {
    aps: {
      alert: message,
      url:   url
    }
  }.to_json
end

def gcm(message, url)
  {
    data: {
      message: message,
      url:     url
    }
  }.to_json
end

sns = Aws::SNS::Client.new(
        access_key_id:     ENV['SNS_ACCESS_KEY_ID'],
        secret_access_key: ENV['SNS_SECRET_ACCESS_KEY'],
        region:            ENV['SNS_REGION']
      )


message_json = {
  default: "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.",
  'APNS': apns("Check out these awesome deals!", "www.amazon.com")
  'GCM' : gcm("Check out these awesome deals!", "www.amazon.com")
}.to_json

sns.publish(
  topic_arn: ENV['SNS_ALL_PUBLISH_TOPIC_ARN'],
  message: message_json
  message_structure: :json
)
7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?