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 runbundle installor just rungem 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: 3Creating Class for Notification
- Create a file in
app\config\initializers\, sayuser_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
endSend Notification
UserNotification.instance.send_notification({
device_token: DEVICE_TOKEN_FOR_DEVICE,
message: YOUR_NOTIFICATION_MESSAGE
})Enjoy!!!!