Created
December 10, 2013 06:29
-
-
Save kalpesh-fulpagare/7886546 to your computer and use it in GitHub Desktop.
Apple Push Notification Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rubygems" | |
require "yajl" | |
require "openssl" | |
require "socket" | |
device_token = '61 DIGIT iPhone_TOKEN' | |
device_token = device_token.gsub(" ", "") | |
the_byte_token = [device_token].pack("H*") | |
file = File.open("ruby_the_byte_token", "wb") | |
file.print(the_byte_token) | |
file.close | |
the_beginning = [0, 0, 32].pack("ccc") | |
file = File.open("ruby_the_beginning", "wb") | |
file.print(the_beginning) | |
file.close | |
def the_payload | |
payload = Hash.new | |
payload['aps'] = Hash.new | |
payload['aps']['alert'] = "Ruby - Oh no! Server\'s Down!" | |
payload['aps']['sound'] = 'k1DiveAlarm.caf' | |
payload['aps']['badge'] = 42 | |
payload['test_data'] = {'foo' => 'bar'} | |
Yajl::Encoder.encode(payload) | |
end | |
the_notification = [0, 0, 32, the_byte_token, 0, the_payload.length, the_payload].pack("ccca*cca*") | |
file = File.open("ruby_the_notification", "wb") | |
file.print(the_notification) | |
file.close | |
def connect | |
cert = File.read('apns-dev.pem') | |
ctx = OpenSSL::SSL::SSLContext.new | |
ctx.key = OpenSSL::PKey::RSA.new(cert, nil) | |
ctx.cert = OpenSSL::X509::Certificate.new(cert) | |
sock = TCPSocket.new('gateway.push.apple.com', 2195) | |
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx) | |
ssl.connect | |
return ssl, sock | |
end | |
def write(ssl, sock, the_notification) | |
ssl.write(the_notification) | |
ssl.flush | |
if IO.select([ssl], nil, nil, 1) | |
error = ssl.read(6) | |
if error | |
error = error.unpack("ccN") | |
puts "ERROR: #{error}" | |
else | |
puts "NO ERROR" | |
end | |
end | |
end | |
def close(ssl, sock) | |
ssl.close | |
sock.close | |
end | |
ssl, sock = connect | |
write(ssl, sock, the_notification) | |
close(ssl, sock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment