Send push based notification on ios devices from rails application

Posted by : on

Category : Rails

How ever in practice we need to send push based notifications on ios devices from the rails application.

For this purpose you can use grocer ruby gem. Here is sample implementation for this:

Install Gem

  • Write gem 'grocer' in you gem file and run bundle install or just run gem install grocer.

Create a yml for notification

  • Create a yml file in config folder on app for settings
development:
  pem_file: YOUR_PEM_FILE_NAME_WITH_ABSOLUTE_LOCATION
  gateway: 'gateway.sandbox.push.apple.com'
  passphrase: 'YOUR_PASS_PHASE'
  port: 2195
  retries: 3
  
test:
  pem_file: YOUR_PEM_FILE_NAME_WITH_ABSOLUTE_LOCATION
  gateway: 'gateway.sandbox.push.apple.com'
  passphrase: 'YOUR_PASS_PHASE'
  port: 2195
  retries: 3

staging:
  pem_file: YOUR_PEM_FILE_NAME_WITH_ABSOLUTE_LOCATION
  gateway: 'gateway.push.apple.com'
  passphrase: 'YOUR_PASS_PHASE'
  port: 2195
  retries: 3

production:
  pem_file: YOUR_PEM_FILE_NAME_WITH_ABSOLUTE_LOCATION
  gateway: 'gateway.push.apple.com'
  passphrase: 'YOUR_PASS_PHASE'
  port: 2195
  retries: 3

Creating Class for Notification

  • Create a file in app\config\initializers\, say user_notifications.rb.
  • Add following lines of code inside user_notifications.rb
require 'singleton'
 
class UserNotification
  include Singleton

  def initialize
    options = YAML.load_file(File.join(Rails.root, 'config', 'apn_settings.yml'))[Rails.env]
    passphrase = options.delete('passphrase')
    gateway = options.delete('gateway')
    port = options.delete('port')
    retries = options.delete('retries')
    _pem_file = options.delete('pem_file')
    @pusher ||= Grocer.pusher(
        certificate: _pem_file,
        passphrase: passphrase,
        gateway: gateway,
        port: port,
        retries: retries
    )
  end

  def send_notification(options)
    puts "------ sending notification on #{options[:device_token]}"
    notification = Grocer::Notification.new(
        device_token: options[:device_token],
        alert: options[:message],
        badge: 42,
        sound: 'siren.aiff'
    )
    @pusher.push(notification)
  end

end

Send Notification

UserNotification.instance.send_notification({
                                                        device_token: DEVICE_TOKEN_FOR_DEVICE,
                                                        message: YOUR_NOTIFICATION_MESSAGE
                                                    })

Enjoy!!!!



About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in