Heroku Rails App 上的 iOS 推送通知 — 如何提供 PEM 文件



我正在尝试从我的Rails应用程序发送推送通知。我尝试了休斯顿的 gems APNS,当我在我的开发机器上时,它们工作得很好。

这些 gem 需要/path/to/PEM/file(Apple 的证书)来发送通知。但是,我似乎无法弄清楚如何在生产服务器上提供此文件。我正在使用Heroku。

我尝试将其上传到Amazon-S3(非公共)并从那里使用它。但是,这不起作用,因为 gem 会查找本地文件(而不是 URI)。如何在 Heroku 上保存本地文件?

gem APNS 需要字符串形式的路径。然后,它会检查该文件是否存在。

raise "The path to your pem file does not exist!" unless File.exist?(self.pem)

休斯顿宝石需要 PEM 作为File对象。但是,我不能做File.open("url_to_my_pem_file")

您可以使用

Rails.root var 来获取本地路径。在 S3 上托管您的证书文件可能有点矫枉过正,您现在正在使您的推送服务器依赖于 S3。如果有停机时间,你不能推动。此外,您将通过拨打网络电话来减慢速度。

这是我的 rails 生产推送服务器的示例方法:

def cert_path
    path = "#{Rails.root}/config/apn_credentials/"
    path += ENV['APN_CERT'] == 'production' ? "apn_gather_prod.pem" : "apn_gather_dev.pem"
    return path    
end

我最终将 AWS-S3 文件复制到 Heroku 应用程序,使用复制的版本(因为它是本地的),然后在发送通知后删除复制的文件。

fname = "tempfile.pem"
# open the file, and copy the contents from the file on AWS-S3
File.open(fname, 'wb') do |fo|
    fo.print open(AWS::S3::S3Object.url_for(LOCATION_ON_S3, BUCKET_NAME)).read
end
file = File.new(fname)
# use the newly created file as the PEM file for the APNS gem
APNS.pem = file 
device_token = '<a4e71ef8 f7809c1e 52a8c3ec 02a60dd0 b584f3d6 da51f0d1 c91002af 772818f2>'
APNS.send_notification(device_token, :alert => 'New Push Notification!', :badge => 1, :sound => 'default')
# delete the temporary file
File.delete(fname)

再三考虑,我本可以使用私有资产,就像这个问题 - 在哪里放置私有文档以在Rails应用程序中使用?,但即使是答案也提到AWS-S3可能是一个更好的主意。

相关内容

最新更新