So you're building the server component of an iPhone application in Ruby. And you want to send background notifications through the Apple Push Notification servers, which doesn't seem too bad. But then you read in the Apple Documentation (Apple Dev account required) that the APN servers may treat non-persistent connections as a Denial of Service attack, and things started looking more complicated.
If this doesn't sound familiar, this gem probably isn't anything you need. If it does, though…
The ApplePushNotification gem includes a background daemon which processes background messages from your application and sends them along to Apple over a single, persistent socket. It also includes helper methods for enqueueing your jobs and a sample monit config to make sure the background worker is around when you need it.
Queueing Messages From Your Application
To queue a message for sending through Apple's Push Notification service from your Rails application:
where token is the unique identifier of the iPhone to receive the message and opts_hash can have any of the following keys:
# :alert #=> The alert to send # :badge #=> The badge number to send # :sound #=> The sound file to play on receipt, or true to play the default sound installed with your app
Getting Messages Actually Sent to Apple
Put your apn_development.pem and apn_production.pem certificates from Apple in your RAILS_ROOT/config/certs directory.
Once this is done, you can fire off a background worker with
$ rake apn:sender
For production, you're probably better off running a dedicated daemon and setting up monit to watch over it for you. Luckily, that's pretty easy:
# To run standard daemon ./script/apn_sender # To pass in options ./script/apn_sender -- --cert-path=PATH_TO_NONSTANDARD_FOLDER_WITH_PEM_FILES --environment=production
Note the –environment must be explicitly set (separately from your RAILS_ENV) to production in order to send messages via the production APN servers. Any other environment sends messages through Apple's sandbox servers at gateway.sandbox.push.apple.com.
Keeping Your Workers Working
There's also an included sample apn_sender.monitrc file in the contrib/ folder to help monit handle server restarts and unexpected disasters.
ApplePushNotification is built on top of Resque (an awesome Redis background runner similar to delayed_job). Read through the Resque README to get a feel for what's going on, follow the installation instructions there, and then run:
$ sudo gem install apple_push_notification
In your Rails app, add
Copyright © 2010 Kali Donovan. See LICENSE for details.