APNS
a gem for the Apple Push Notification Service.
Install
sudo gem install ja-apns
Setup:
Convert your certificate
In Keychain access export your certificate as a p12. Then run the following command to convert it to a .pem
openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
After you have your .pem file. Set what host, port, certificate file location on the APNS class:
sender = APNS::Sender.new({
# gateway.sandbox.push.apple.com is default
host: 'gateway.push.apple.com',
# this is the file you just created
pem: '/path/to/pem/file',
# this is also the default. Shouldn't ever have to set this, but just in case Apple goes crazy, you can.
port: 2195
})
Example:
You will need to create a notification class and provide the following instance methods:
device_token
, alert
, badge
, sound
, other
, valid?
class MyNotification
def device_token
'your token'
end
alert
'Hello iPhone'
end
badge
1
end
sound
'default'
end
def other
{foo: 'bar'}
end
def valid?
true
end
end
sender = APNS::Sender.new
notification = MyNotification.new
sender.send_notifications([notification])
Getting your iPhone’s device token
After you setup push notification for your application with Apple. You need to ask Apple for you application specific device token.
ApplicationAppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Register with apple that this app will use push notification
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
// Your app startup logic...
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// Convert the binary data token into an NSString (see below for the implementation of this function)
NSString *deviceTokenAsString = stringFromDeviceTokenData(deviceToken);
// Show the device token obtained from apple to the log
NSLog(@"deviceToken: %@", deviceTokenAsString);
}
stringFromDeviceTokenData function
This snippet comes from this stackoverflow post’s anwser.
NSString* stringFromDeviceTokenData(NSData *deviceToken)
{
const char *data = [deviceToken bytes];
NSMutableString* token = [NSMutableString string];</p>
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:@"%02.2hhX", data[i]];
}
return [[token copy] autorelease];
}
</code>
<p>
For more information on Apple Push Notifications you can see Apple Developer Documentation here.