Sending apple push notification with ApplePush gem
One day i was looking for a simple way to deliver notification to devices via apple push notifications service (APN). There are bunch of solutions on the market, rails plugins, gems or even third-party services like UrbanAirship, which by the way does a great job. But i was looking for something that could be useful for development and staging purposes.
My the target list was something like that:
- Easy to install and integrate
- Multiple environments (send to sandbox and live endpoints)
- Small codebase
- Based on EventMachine
After playing around with different gems (some of them are old or no longer supported) i decided to create a simple sinatra-based app that provided me everything i outlined above.
Checkout apple_push on Github: https://github.com/sosedoff/apple_push
ApplePush Gem
The whole concept behind it was to create an API that could support multiple environments with flexible connections pool and be separate from the app, only having a simple API client. It could be used with foreman, which is really handy if you want to run the whole app stack together.
Based on em-apn
, connection_pool
and eventmachine
gems.
Install it via rubygems:
gem install apple_push
Create a simple configuration:
host: 127.0.0.1
port: 27000
sandbox:
cert: path/to/your/certificate.pem
key: path/to/your/key.pem
pool: 1
live:
cert: path/to/your/certificate.pem
key: path/to/your/key.pem
pool: 1
In the example above i configured sandbox and live environments for my app. You can obtain certificates and keys using apple application panel, im not familiar with that :) At least once environment is required in order to start the server. That's about it.
Now, start the server daemon:
apple_push path/to/your/config.yml
If everything is fine, you'll see something like this:
>> Thin web server (v1.3.1 codename Triple Espresso)
>> Maximum connections set to 1024
>> Listening on 127.0.0.1:27000, CTRL+C to stop
API Usage
Since apple_push is a pretty standard sinatra application, there are no extra tools to install in order to start using the api.
It offers just 2 routes:
POST /live
POST /sandbox
Test delivery with curl: (TOKEN param is your device token)
curl -X POST -d '{"alert":"Test Message"}' "http://localhost:27000/live?token=TOKEN"
Example faraday-based client could be found here: https://github.com/sosedoff/apple_push/blob/master/examples/apple_push_client.rb
Using with Foreman
If you'd like to use apple_push server with foreman, you'll need to create a Procfile
:
apn: apple_push config/apn.yml