Michael Peralta
Michael Peralta

Reputation: 293

Apple Push Notifications Rails App Messaging

I want to send an apple push notification every time a user gets a new message. I found this tutorial http://www.waratuman.com/2011/01/13/apple-push-with-heroku/

and with this code

 class Jobs::APN::DeliverNotifications
   @queue = "apn"

   def self.perform
      APN::Notification.send_notifications
   end

 end

 class Jobs::APN::Feedback < Job
   @queue = "#{RAILS_ENV}::apn"

   def self.perform
     APN::Feedback.process_devices
   end

 end

 class Api::ApnController < ApplicationController
   skip_before_filter :verify_authenticity_token

   def create
     APN::Device.create(:token => params[:token])
     render :text => "", :status => 200
   end

   def subscribe
     device = params['token'] ? APN::Device.find_or_create_by_token(:token =>  params['token']) : nil
     event = Event.first(:conditions => {:id => params['event_id']})
     subscription = Subscription.new :device => device, :event => event

     status = 200
     if device && event && subscription.valid?
       subscription.save
     else
       status = 422
     end
     render :text => "", :status => status
   end

   def unsubscribe
     device = APN::Device.find_or_create_by_token(:token => params['token'])
     event = Event.first(:conditions => {:id => params['event_id']})
     subscription = Subscription.first(:conditions => {:device_id => device.id, :event_id => event.id})
     subscription.delete if subscription
     render :text => "", :status => 200
   end

 end

I know this code is supposed to set up the notifications and register the device but when I actually want to send a notification for a new message what should I do?

I currently have a message index

   def index
     if params[:mailbox] == "sent"
       @messages = @user.sent_messages
     elsif params[:mailbox] == "unread"
       @messages = @user.received_messages.unread
     else
       @messages = @user.received_messages
     end


     respond_to do |format|
       format.html
       format.json { render :json => @messages }
     end
   end

so the unread path will show all my unread messages for a specific user. I want to send those as a push notification. Any advice? I'm still learning so excuse the vagueness.

Upvotes: 2

Views: 1279

Answers (1)

Moustafa Samir
Moustafa Samir

Reputation: 2268

From this tutorial

You can create a notification using:

device = #load your device
notification = APN::Notification.new   
notification.device = device   
notification.badge = 5   
notification.sound = true   
notification.alert = "My first push"   
notification.save 

this will only create a notification and store it, so tot actually send the notification run this rake task

rake apn:notifications:deliver  

or call this function

APN::App.send_notifications

Upvotes: 1

Related Questions