Skip to content

Instantly share code, notes, and snippets.

@jbmyid
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbmyid/3e3e5815ac137c87c8d5 to your computer and use it in GitHub Desktop.
Save jbmyid/3e3e5815ac137c87c8d5 to your computer and use it in GitHub Desktop.
Push Notification with AWS SNS Service
Prerequisites
1. Amazon account
2. Note Down the Amazon access_key_id, secret_access_key and region
3. Create an Application in Amazon/SNS Section
4. Note Down the Application Platform ARN
5. Set ENV variables:
ENV['SNS_APP_ARN'] = the arn obtained from 4th step
ENV['AWS_ACCESS_KEY_ID'] = obtained from step 2
ENV['AWS_SECRET_ACCESS_KEY']= obtained from step 2
Getting Started with 'aws-sdk' gem
1. Add gem 'aws-sdk'
2. bundle install
3. Set configuration for aws
AWS.config(access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], region: <region>)
4. Create an sns object
sns = AWS::SNS.new
5. Set sns client
client = sns.client
6. Whenever device registers on your site get GCM registration id and store it in your database, and every time the gmc registration id changes subscribe it in SNS
response = client.create_platform_endpoint token: gcm_registraion_id, platform_application_arn: ENV['SNS_APP_ARN']
# the response will contain the end_point_arn for the device registered, which will be used in sending notifications
device_arn = response[:endpoint_arn] # save it
Publishing Notification:
gcm_message = {collapse_key: "any_collapse_key", data: {key: "Value"}}
message = {"GCM"=> gcm_message.to_json}.to_json
response = client.publish target_arn: "<device_arn>", message: message , message_structure: 'json'
Notification Sent!
Whenever gcm registration id changes remove the existing target_arn and add new one
To remove the existing target arn
client.delete_endpoint(endpoint_arn: device_arn)
You can broad cast the notification with by creating topics and subscribing the arn to the particular topics and publish specifying topic_arn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment