Lチカ開発ブログ

https://l-chika.com/の開発ブログ

RubyでAWS SNS からiOSにプッシュ通知

サーバーからiOS端末にPUSH通知を送る

前提

  • IAMでSNS権限があるユーザを作成されている
  • バイストークンを取得している
  • SNSでApplicationのArnが作成されている
require 'aws-sdk'
require 'json'

aws_access_key = 'IAMのaccessKeyを設定'
aws_secret_key = 'IAMのsecret_keyを設定'

sns = Aws::SNS::Client.new(
  access_key_id: aws_access_key,
  secret_access_key: aws_secret_key,
  region: 'ap-northeast-1'
)

token = "デバイスのトークン"

# endpointの作成。SNSで設定したApplicationのArn
app_arn = "arn:aws:sns:xxxxx"

resp = sns.create_platform_endpoint(
  platform_application_arn: app_arn,
  token: token
)

apns_payload = {
    'aps' => {
        'alert' => 'ほげほげ',
        'sound' => 'default',
        'content-available' => 1,
    }
}

# Push Notification Platformが
#「Apple Development」の場合は 「APNS_SANDBOX」
#「Apple Ploduction」の場合は「APNS」
message = { "APNS_SANDBOX" => apns_payload.to_json }.to_json


sns.publish(
  target_arn: resp.endpoint_arn,
  message: message,
  message_structure: 'json'
)

参考

Amazon Web Services クラウドネイティブ・アプリケーション開発技法 (Informatics&IDEA)

Amazon Web Services クラウドネイティブ・アプリケーション開発技法 (Informatics&IDEA)