Skip to content

Instantly share code, notes, and snippets.

@brcosm
Created September 13, 2011 02:41
Show Gist options
  • Save brcosm/1213023 to your computer and use it in GitHub Desktop.
Save brcosm/1213023 to your computer and use it in GitHub Desktop.
Ruby Apple Push Notification Example
require 'openssl'
require 'socket'
require 'rubygems'
require 'json'
# Takes json as an input and sends data to APNS over SSL
APNS_HOST = 'gateway.sandbox.push.apple.com'
APNS_PORT = 2195
APNS_CERT_FILE_PATH = 'MyCert.pem'
APNS_CERT = File.read(APNS_CERT_FILE_PATH) if File.exists?(APNS_CERT_FILE_PATH)
DEVICE_TOKEN = "12345abc 12345abc 12345abc 12345abc 12345abc 12345abc 12345abc 12345abc"
# Create the SSL connection
def create_socket
context = OpenSSL::SSL::SSLContext.new
context.key = OpenSSL::PKey::RSA.new(APNS_CERT,'')
context.cert = OpenSSL::X509::Certificate.new(APNS_CERT)
socket = TCPSocket.new(APNS_HOST, APNS_PORT)
ssl = OpenSSL::SSL::SSLSocket.new(socket,context)
ssl.connect
return socket, ssl
end
# Send the actual notification which is some json data
def send_notification(socket, ssl, payload)
token = [DEVICE_TOKEN.delete(' ')].pack('H*')
msg = "\0\0 #{token}\0#{payload.length.chr}#{payload}"
begin
ssl.write(msg)
ssl.flush
puts "Sending payload: #{payload}"
rescue
puts "Socket error occurred, retrying connection"
end
end
socket, ssl = create_socket
# Get json data from input
payload = {"aps" => {"alert" => ARGV[0]}, "ord" => {"shp" => ARGV[1], "section" => ARGV[2], "row" => ARGV[3]}}
json = payload.to_json()
send_notification(socket, ssl, json)
ssl.close
socket.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment