Ruby on Rails,Grocer无法发送推送通知多个收件人

时间:2014-10-15 00:58:54

标签: ios ruby-on-rails ruby apple-push-notifications

  def push_notification(users)

    unless self.pushed_to_mobile? || users.empty?

      # make sure all required users receive notifications on
      # all registered devices.
      @device_tokens = users.map { |u| u.device_tokens }.flatten.uniq

      @device_tokens.each do |token|

        notification = Grocer::Notification.new(
          device_token:   token.device_token,
           alert:        { "body" => "#{self.context_type}: #{self.name}", "action-loc-key" => "View" },
           badge:        1,
           sound:        'chord.aiff'
           custom:       { "content" => [ self.name, self.context_type, self.context_name, self.context_id, self.content_id ] },
        )

        feedback.each do |attempt|
        #   # TODO: if a device fails 3 times it should be removed from the token list.
        #   # Failing 3 times indicates that the user has turned notifications off or
        #   # removed the app from the phone. If the user logs in and their token does
        #   # not exist it will be readded.
          puts "Device #{attempt.device_token} failed at #{attempt.timestamp}"
        end

        pusher.push( notification )

      end
    end

    # update model to prevent notifying again.
    self.pushed_to_mobile = true
    self.save
  end

  def pusher
    return @pusher if defined?( @pusher )
    @pusher = Grocer.pusher(
      certificate: Settings.apple_push_notification_options[:certificate],
      passphrase:  Settings.apple_push_notification_options[:pass],
      gateway:     Settings.apple_push_notification_options[:host],
      retries:     3
    )
  end

  def feedback
    return @feedback if defined?( @feedback )
    @feedback = Grocer.feedback(
      certificate: Settings.apple_push_notification_options[:certificate],
      passphrase:  Settings.apple_push_notification_options[:pass],
      gateway:     Settings.apple_push_notification_options[:host],
      retries:     3
    )
  end

如果我删除循环并强制将代码发送到单个令牌,则代码会运行并在设备上收到推送通知。但是,如果我尝试遍历users.device_tokens数组,则代码执行时没有错误,但是设备上从未收到通知。

编辑:即使循环仅在其工作时运行。

1 个答案:

答案 0 :(得分:3)

问题与您访问Grocer::Feedback套接字的方式有关。请尝试将feedback方法更改为以下内容。

def feedback
  @feedback ||= Grocer.feedback(
    certificate: Settings.apple_push_notification_options[:certificate],
    passphrase:  Settings.apple_push_notification_options[:pass],
    gateway:     Settings.apple_push_notification_options[:host],
    retries:     3
  )
  @feedback.to_a
end

调用to_a将强制读取反馈套接字上当前的内容。