2

每次用户收到新消息时,我都想发送一个苹果推送通知。我找到了这个教程http://www.waratuman.com/2011/01/13/apple-push-with-heroku/

并使用此代码

 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

我知道这段代码应该设置通知并注册设备,但是当我真的想为新消息发送通知时,我应该怎么做?

我目前有一个消息索引

   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

因此未读路径将显示特定用户的所有未读消息。我想将它们作为推送通知发送。有什么建议吗?我还在学习,所以请原谅含糊不清。

4

1 回答 1

1

本教程

您可以使用以下方法创建通知:

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

这只会创建一个通知并存储它,所以实际上发送通知运行这个 rake 任务

rake apn:notifications:deliver  

或调用此函数

APN::App.send_notifications
于 2013-04-18T22:45:49.710 回答