Sending iOS push notifications from a Rails application is very easy to do these days, thankfully there are many great Ruby gems that can be used to handle most of the magic for you. Recently I ran into the apn_sender gem which handles sending push notifications in a really neat way.

Sending push notifications directly from a Rails application can be slow and we probably don’t want to have the user waiting until the notification is sent, instead apn_sender can be setup to run a worker which is constantly connected to the apple push notification service. When there are new notifications to send, the notifications are queued up and sent through the always open connection that is maintained by the worker.

apn_sender uses redis as a message queue to keep track of the notifications waiting to be sent, you’ll need to install it before using the gem.

To add apn_sender in your Rails 3 application, just add the gem to your Gemfile. We’re going to need the daemons gem too so we’ll include that as well.

Can’t see this Gist? View it on Github!

Now we can create our daemon which we will be using for sending push notifications, this can be placed anywhere, I’ve put mine in script/apn_sender. Make sure to add execute permission to the file after creating so we can run it.

Can’t see this Gist? View it on Github!

Before the daemon can start running we’ll need to put our iOS push certificate into the application. Instructions for generating the certificates are available at the Apple Developer site. The certificates need to be placed inside of /config/certs and should be named apn_development.pem or apn_production.pem for production.

Once the certificates are in their correct locations, we can start up the daemon. The daemon does not know about the Rails environment so we need to specify this when starting it up. The daemon supports start, stop and restart commands. There is a verbose flag available to output more information (which can be helpful when debugging).

Can’t see this Gist? View it on Github!

Our application is now set up to send push notifications, this can now easily be performed by adding a new notification to the queue. The notify method on the APN class will take a push notification token and then our parameters, we can specify the alert message to show the user, whether or not we want sound as well as the number to display on the badge icon. Anything else we pass to notify will be sent as metadata in the push notification. Here’s an example of creating a notification.

Can’t see this Gist? View it on Github!

The worker should pick up the notification within a few seconds and send it off. The apn_sender has many other features that I haven’t covered, you can view the full documentation over at https://github.com/kdonovan/apn_sender.