Friday, 19 February 2016

Sending push notification with APNS(Apple push notifications service) and rails

Hello There, I got a problem in which I have to send the push notification on iphones when some event occurs by the rails application. For this I have used rubygem 'grocer'. Here is the sample implementation for this:

1. Introduction: 

APNS(Apple Push Notification Service) The Apple Push Notification Service (APNs) is a service created by Apple Inc. that forwards notifications of third party applications to the Apple devices; such notifications may include badges, sounds or custom text alerts. It was launched together with iOS 3.0 on June 17, 2009.[1] In iOS 5's Notification Center added pushing local notifications. APNs was also added as an API to Mac OS X v10.7 "Lion" for developers to take advantage of,[2] and was improved in OS X 10.8 "Mountain Lion" with the introduction of Notification Center.

Apple announced the service on June 9, 2008 with a stated release for that September; however, as stated by Scott Forstall at the iOS 3.0 preview event on March 17, 2009, the rollout was delayed after a decision to restructure the APNs for scalability purposes due to the allegedly "overwhelming" response to the announcement of the APNs. At both events, Forstall stated that push notifications better conserve battery than background processes (which are used in pull technology) for receiving notifications.

2. Install Gem: 

Follow these steps:
1. install Gem by using `gem install grocer`. or write `gem 'grocer'` in side your Gemfile and run 
'bundle install'.

3. Sending notifications:

a. Create a pusher object to send notifications:
  @pusher ||= Grocer.pusher(
      certificate: _pem_file,
      passphrase: passphrase,
      gateway: gateway,
      port: port,
      retries: retries  )

where _pem_file => is the location of your certificate.pem file.
passphrase => is the passphrase while creating the pem file.
gateway => 
1.For development and staging: 'gateway.sandbox.push.apple.com'
2. For production : 'gateway.push.apple.com'

port => 2195
retries => is maximum number of retries.

b. Create notification object:

notification = Grocer::Notification.new(
    device_token: YOUR_DEVICE_TOKEN,
    alert: YOUR_MESSAGE,
    badge: 42,
    sound: 'siren.aiff')

where device_token is the device token on which you want to send the notification.

c. Send Notifications: 
@pusher.push(notification)

this will send a notification on your given device.

Thanks for reading this blog.

No comments:

Post a Comment