Sending Push Notifications to iOS and Android Applications With Ruby on Rails

Push Notification with Hybrid appA few days ago I created the article describing how to implement push notifications for iOS and Android for you hybrid mobile app. Now it’s time to discribe server-side. Usually I’m using Rails for server-side, so this example will be about Rails.

Sending push notifications with Rails is quite easy, but have some nuances, which should be implemented.

Android Prerequisites

  • API Key for Google Cloud Messaging (the same link, choose “Enable API” section and create server key)

iOS Prerequisites

  • iOS developer account
  • Push certificate (.pem format). Separate certificates are required for development and production environments

How to setup push notifications

  • Install gems to handle Google and Apple servers communication

    • Each device will have it’s unique device registration id. This id will be sent to server from mobile app. Also we need to save device type (‘ios’ / ‘android’). Let’s use the sample model

  • Now create static method for Device class. This method will send push notification to all Android devices.

collapse_key is an arbitrary string (such as “Updates Available”) that is used to collapse a group of like messages when the device is offline, so that only the last message gets sent to the client. This is intended to avoid sending too many messages to the phone when it comes back online.

data is an arbitrary Ruby hash, can contain different parameters. But :title and :message will be displayed on device screen. Please refer GCM docs to see detailed description

  • And another method is required to send notification to iOS devices

  • Please note, that sending push notifications to iOS devices requires feedback service implementation. This service returns device registration ids, which must never be more used to send notifications. Here is the sample implementation:

Good idea is to run this code (APNClient.apple_feedback) at daily basis.

Apple documentation about push notifications recommends to avoid often connections/disconnections to their servers, so if you’re planning to send a lot of notifications, you’ll need to setup persistent connection to Apple push notifications server. If you’re not planning to send a lot of notifications, you can connect and disconnect each time. But I’m not sure what “not planning to send a lot of notifications” mean (1/day, 10/day, 100/day). Keep an eye on updates, I’m planning to write a post how to setup a persistent connection.

One thought on “Sending Push Notifications to iOS and Android Applications With Ruby on Rails”

Leave a Reply

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