Using Ruby on Rails and AWS SNS to send APNS

SNS from AWS now offers a great way to send mobile APNS messages to your users. Sure you can blow away money with urban airship. The great part is that AWS can keep track of endpoints that fail, does a queue system for you and AWS gives great error messages back when a APNS fails. Before we would have to read in a stream from apple’s push notification servers to see if the message failed and deal with all the bizarre time outs. The cost with AWS SNS is really cheap as well.

Setting up a SNS app

To setup an app simply open up your p12 file and copy paste the two sections of your p12 file into these boxes below on AWS. You can open your p12 file by using just an editor like VI.

Screen Shot 2014-03-17 at 8.34.02 PM

Setting up SNS AWS

Create endpoints. Once you have an app setup with the correct p12 / pem file you can now create endpoints. An endpoint is a APNS token that can hold a value. We place the account_id into this value. In the image below you can see a User Data field. We add the account_id into that column.

Screen Shot 2014-03-17 at 8.27.05 PM

Code Time

First you want to get the AWS gem for ruby and install it. Once you have it installed you can try and setup an endpoint from the API. The code looks complicated but the only thing it is doing is getting an endpoint with the apns token passed from the mobile client.

arn = 'arn:aws:sns:us-east-1::app/APNS/.iOS.Production'
endpoint = AWS.sns.client.create_platform_endpoint :platform_application_arn => arn, :token => params[:apns_token from_mobile_device], :custom_user_data => user.id, :attributes => {}

Now you have an endpoint. With this you can message away.

out_message = {:m=>"Hi",:someotherdata=>"f19b9"}
apns_string[:aps] = {:alert => out_message, :sound => 'receive_message.wav', :badge => 1 }
aws_message = {:default => out_message,:APNS => apns_string.to_json}

AWS.sns.client.publish :message => aws_message.to_json, :target_arn => endpoint, :message_structure => 'json'

Cool parts of the AWS GUI.

You can publish / send an sms right there in the GUI. You can also see what tokens are enabled and disabled. Before you had to keep track of all these your self in a monster mySQL table.

Screen Shot 2014-03-17 at 8.56.41 PM

One thought on “Using Ruby on Rails and AWS SNS to send APNS

  1. admin Post author

    Hey,
    AWS.sns.client.create_platform_endpoint: It creates an endpoint. You can see below were we add the token: YOUR_DEVICE_TOKEN

    endpoint = AWS.sns.client.create_platform_endpoint
    :platform_application_arn => arn,
    :token => [YOUR_DEVICE_TOKEN],
    :custom_user_data => user.id,
    :attributes => {}

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


6 − four =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>