Apple PNS (push notification services) sample code

95,095

Solution 1

The worst part about setting up the push notification service is the provisioning. The major stumbling block that I came across was that there is a certificate and a key in the .cer file you download from Apple's site, I wrote a system service in C# that sent out notifications and the connections kept failing because I had exported the certificate and not the key.

I don't recall who originally wrote this, here is a little bit of code in python that helped me out when I was first testing the notification service. I like it because it is very simple and works well during testing.

import socket, ssl, json, struct

# device token returned when the iPhone application
# registers to receive alerts

deviceToken = 'XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX' 

thePayLoad = {
     'aps': {
          'alert':'Oh no! Server\'s Down!',
          'sound':'k1DiveAlarm.caf',
          'badge':42,
          },
     'test_data': { 'foo': 'bar' },
     }

# Certificate issued by apple and converted to .pem format with openSSL
# Per Apple's Push Notification Guide (end of chapter 3), first export the cert in p12 format
# openssl pkcs12 -in cert.p12 -out cert.pem -nodes 
#   when prompted "Enter Import Password:" hit return
#
theCertfile = 'cert.pem'
# 
theHost = ( 'gateway.sandbox.push.apple.com', 2195 )

# 
data = json.dumps( thePayLoad )

# Clear out spaces in the device token and convert to hex
deviceToken = deviceToken.replace(' ','')
byteToken = bytes.fromhex( deviceToken ) # Python 3
# byteToken = deviceToken.decode('hex') # Python 2

theFormat = '!BH32sH%ds' % len(data)
theNotification = struct.pack( theFormat, 0, 32, byteToken, len(data), data )

# Create our connection using the certfile saved locally
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )
ssl_sock.connect( theHost )

# Write out our data
ssl_sock.write( theNotification )

# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()

There's also a rails gem called apn_on_rails that seems to work pretty well if you're developing a rails application, I just saw it today and was able to send out notifications from the console.

On the iPhone side you'll just need to call the following to register for all types of notifications:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];

To receive the device token you'll need to implement the following delegate methods:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

During testing you can just kick the deviceToken to the console with NSLog, then paste it into the python script above, in production you'll obviously need to set up some method to get the token to your servers.

Also, in production you'll need to query Apple's feedback service and remove device tokens from users who removed your app.

Solution 2

A good place to start is Urban Airship. You can set up a free basic account that will do all of the server-side work of sending push notifications to Apple's servers. They also do a great job of walking you through all of the steps needed to get your application working with their service, and have excellent sample code that shows how to register your application for notifications.

I have no other affiliation with them other than being a happy user of their service.

Solution 3

In case it helps, I've written a Python library, PyAPNs, for interacting with the Push Notification Service on the server side:

http://github.com/simonwhitaker/PyAPNs

Solution 4

http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/

This one helped me a lot with making provider side code on linux server with PHP.

Solution 5

There really isn't much code to write on the iPhone side. You need to get the unique token of the iPhone or iPod Touch and then relay that token to your server. Getting the token requires a call to UIApplication but there's no predefined way of getting that to your server. One of my apps performs an HTTP POST to a PHP script that puts the token into a database.

If you're curious about provisioning and the setup of the certificates, etc..., you might check out the Apple Push Notification Service Programming Guide.

Share:
95,095
froh42
Author by

froh42

Updated on September 04, 2020

Comments

  • froh42
    froh42 almost 4 years

    Is there a sample project showing how to use APNS on the IPhone and how to set up things? I'm currently looking at the documentation but it would be nice to have some working code to pick apart and see how it all works together?

    I can't seem to find anything using google or in the iphone dev center.

  • froh42
    froh42 about 15 years
    Ben, yes it does not look to complicated from the documentation and I'm also positive I'll work out the provisioning (haven't looked at that, yet ...) It would have been just nice to have a step-by-step example of how to set up things.
  • pm_labs
    pm_labs about 14 years
    I'm also currently going this route as most shared hosting do not allow connection to Apple's custom ports for push notifications. I remember seeing a Python program for Google App Engine before which sends out REST requests to Urban Airship (useful for cron based notifications) but I can't seem to find it at the moment. Please let me know if you guys stumble upon it. Thanks!
  • pm_labs
    pm_labs about 14 years
    Word of caution: most shared hosting do not have the ports open specific for APNS. So if you want to go this route, you might need to have it hosted in a VPS at least.
  • Joe McMahon
    Joe McMahon about 14 years
    Yes, their service works well. They've expanded to a true store-and-forward service called AirMail which takes most of the work off the backend - all it needs to do now is send JSON with embedded HTML to the Urban Airship servers; they take care of sending the notifications and serving up the HTML when requested.
  • David Underhill
    David Underhill over 13 years
    Check out Simon's answer below - he's wrapped up the Python code in a nice library which you can get here: github.com/simonwhitaker/PyAPNs
  • Devang
    Devang about 13 years
    Hey can you please help me for implementing Urban Airship API in my iPhone app ? see what problem i'm getting is : stackoverflow.com/questions/5634125/… i hope that you must be having some solution. thanks
  • David K. Hess
    David K. Hess over 10 years
    WARNING - this code is for version 0 of the protocol. Apple is now up to version 2.
  • jessecurry
    jessecurry over 10 years
    Since writing this answer I've moved almost entirely to Urban Airship to provide push notification services. I've heard some good reviews for helios.io but have never used it myself.
  • liv a
    liv a over 10 years
    @jessecurry Thank you so much for this, two additional questions, using above code is there a way to send a notification to all my users without going in a loop? is there a step by step tutorial for implementing airship on the python server side, can you share your code?
  • TomSawyer
    TomSawyer about 3 years
    line: theNotification = struct.pack(theFormat, 0, 32, byteToken, len(data), data) got error: struct.error: argument for 's' must be a bytes object