转自:https://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/

One of the widely anticipated features of the new iPhone OS 3.0 ispush notifications which allow messages to be sent directly to an individual device relevant to the application that has been installed. Apple have demoed this as useful for news alerts, or IM notifications however it fits in perfectly with the nature of our server monitoring service, Server Density.

As part of the product, we have an iPhone application that includes push notifications as an alerting option so you can be notified via push direct to your iPhone when one of your server alerts have been triggered. This is useful since our app can then be launched to instantly see the details of the server that has caused the alert.

Apple provides detailed code documentation for the iPhone OS codethat is needed to implement and handle the alerts on the device but only provides a higher level guide for the provider server side.

As a provider, you need to communicate with the Apple Push Notification Service (APNS) to send the messages that are then pushed to the phone. This is necessary so that the device only needs to maintain 1 connection to the APNS, helping to reduce battery usage.

This tutorial will go into code-level detail about how we built our push notification provider server to allow us to interact with the APNS and use the push notifications with our server monitoring iPhone application. Since we develop in PHP, our examples will be in PHP 5.

Basic Structure

  1. You connect to the APNS using your unique SSL certificate
  2. Cycle through the messages you want to send (or just send 1 if you only have 1)
  3. Construct the payload for each message
  4. Disconnect from APNS

The flow of remote-notification data is one-way. The provider composes a notification package that includes the device token for a client application and the payload. The provider sends the notification to APNs which in turn pushes the notification to the device.

Apple documentation

Restrictions

  • The payload is limited to 256 bytes in total – this includes both the actual body message and all of the optional and additional attributes you might wish to send. Push notifications are not designed for large data transfer, only for small alerts. For example we only send a short alert message detailing the server monitoring alert triggered.
  • APNS does not provide any status feedback as to whether your message was successfully delivered. One reason for this is that messages are queued to be sent to the device if it is unreachable, however only the last sent message will be queued – overwriting any previously sent but undelivered messages.
  • Push notifications should not be used for critical alerts because the message will only be delivered if the device has wifi or cellular connectivity, which is why we recommend combining push with another alerting method such as e-mail or SMS for our server monitoring alerts.
  • The SSL certificates used to communicate with APNS, discussed below, are generated on an application level. The implementation discussed in this tutorial only concerns a single iPhone application so if you have several, you will need to adapt the code to use the appropriate certificate(s) where necessary.

Device Token

Each push message must be “addressed” to a specific device. This is achieved by using a unique deviceToken generated by APNS within your iPhone application. Once this token has been retrieved, you need to store it on your server, not within your iPhone application itself. It looks something like this:

c9d4c07c fbbc26d6 ef87a44d 53e16983 1096a5d5 fd825475 56659ddd f715defc

For the Server Density iPhone application, we call the necessary generation methods on app launch and pass it back to our servers via an HTTP API call. This stores the deviceToken in a database on our servers for that user so we can then communicate with the device linked to that user.

Feedback Service

Apple provide a feedback service which you are supposed to occasionally poll. This will provide a list of deviceTokens that were previously but are no longer valid, such as if the user has uninstalled your iPhone application. You can then remove the deviceToken from your database so you do not communicate with an invalid device.

Using the feedback service is not covered by this tutorial.

Certificates

The first thing you need is your Push certificates. These identify you when communicating with APNS over SSL.

Generating the Apple Push Notification SSL certificate on Mac:

  1. Log in to the iPhone Developer Connection Portal and click App IDs
  2. Ensure you have created an App ID without a wildcard. Wildcard IDs cannot use the push notification service. For example, our iPhone application ID looks something likeAB123346CD.com.serverdensity.iphone
  3. Click Configure next to your App ID and then click the button to generate a Push Notification certificate. A wizard will appear guiding you through the steps to generate a signing authority and then upload it to the portal, then download the newly generated certificate. This step is also covered in the Apple documentation.
  4. Import your aps_developer_identity.cer into your Keychain by double clicking the .cer file.
  5. Launch Keychain Assistant from your local Mac and from the login keychain, filter by the Certificates category. You will see an expandable option called “Apple Development Push Services”
  6. Expand this option then right click on “Apple Development Push Services” > Export “Apple Development Push Services ID123″. Save this as apns-dev-cert.p12 file somewhere you can access it.
  7. Do the same again for the “Private Key” that was revealed when you expanded “Apple Development Push Services” ensuring you save it as apns-dev-key.p12 file.
  8. These files now need to be converted to the PEM format by executing this command from the terminal:
    1. openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
    2. openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
  9. If you wish to remove the passphrase, either do not set one when exporting/converting or execute:
    1. openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
  10. Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:
    1. cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem

It is a good idea to keep the files and give them descriptive names should you need to use them at a later date. The same process above applies when generating the production certificate.

Payload Contents

The payload is formatted in JSON, compliant with the RFC 4627 standard. It consists of several parts:

  • Alert – the text string to display on the device
  • Badge – the integer number to display as a badge by the application icon on the device home screen
  • Sound – the text string of the name of the sound to accompany the display of the message on the device
  • This tutorial will only deal with the basics by sending a simple alert text string but this can also be another dictionary containing various options to display custom buttons and the like.

Creating the payload

Using PHP it is very easy to create the payload based on an array andconvert it to JSON:

  1. $payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
  2. $payload = json_encode($payload);

Echoing the contents of $payload would show you the JSON string that can be sent to APNS:

  1. {
  2. "aps" : { "alert" : "This is the alert text", "badge" : 1, "sound" : "default" }
  3. }

This will cause a message to be displayed on the device, trigger the default alert sound and place a “1″ in the badge by the application icon. The default buttons “Close” and “View” would also appear on the alert that pops up.

For the Server Density server monitoring iPhone application, it is important for the user to be able to tap “View” and go directly to the server that generated the alert. To do this, we add an extra dictionary in of our own custom values:

  1. $payload['aps'] = array('alert' => 'This is the alert text', 'badge' => 1, 'sound' => 'default');
  2. $payload['server'] = array('serverId' => $serverId, 'name' => $name);
  3. $output = json_encode($payload);

The custom dictionary server is passed to the application on the device when the user taps “View” so we can load the right server. The JSON looks like this:

  1. {
  2. "aps" : { "alert" : "This is the alert text", "badge" : 1, "sound" : "default" },
  3. "server" : { "serverId" : 1, "name" : "Server name")
  4. }

The size limit of 256 bytes applies to this entire payload, including any custom dictionaries.

The raw interface

Once an alert is generated within Server Density, the payload is built and then inserted into a queue. This is processed separately so that we can send multiple payloads in one go if necessary.

Apple recommends this method because if you are constantly connecting and disconnecting to send each payload, APNS may block your IP.

As described by Apple:

The raw interface employs a raw socket, has binary content, is streaming in nature, and has zero acknowledgment responses.

Opening the connection

The PHP 5 code to open the connection looks like this:

  1. $apnsHost = 'gateway.sandbox.push.apple.com';
  2. $apnsPort = 2195;
  3. $apnsCert = 'apns-dev.pem';
  4.  
  5. $streamContext = stream_context_create();
  6. stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
  7.  
  8. $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);

If an error has occurred you can pick up the error message from$errorString. This will also contain the details if your SSL certificate is not correct.

The certificate file is read in relative to the current working directory of the executing PHP script, so specify the full absolute path to your certificate if necessary.

Note that when testing you must use the sandbox with the development certificates. The production hostname isgateway.push.apple.com and must use the separate and different production certificate.

Sending the payload

At this point, the code we use loops through all the queued payloads and sends them. Constructing the binary content to send to APNS is simple:

  1. $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload;
  2. fwrite($apns, $apnsMessage);

Note that the $deviceToken is included from our database and stripped of the spaces it is provided with by default. We also include a check to send an error to us in the event that the $payload is over 256 bytes.

$apnsMessage contains the correctly binary formatted payload and thefwrite call writes the payload to the currently active streaming connection we opened previously, contained in $apns.

Once completed, you can close the connection:

  1. socket_close($apns);
  2. fclose($apns);

php-apns

There is a free, open source server library that does all the above functionality called php-apns. We chose to implement it ourselves because it has a further dependancy on memcached, we do not want to rely on 3rd party code for large and critical aspects of our code-base and I am apprehensive about the suitability of PHP for running a continuous server process. We do all the above queue processing using our own custom cron system which runs every few seconds – that way PHP scripts do not need to be run as processes, something I’m not sure they were designed to do!

All done

(转)How to build an Apple Push Notification provider server (tutorial)的更多相关文章

  1. (转)Apple Push Notification Services in iOS 6 Tutorial: Part 2/2

    转自:http://www.raywenderlich.com/32963/apple-push-notification-services-in-ios-6-tutorial-part-2 Upda ...

  2. (转)Apple Push Notification Services in iOS 6 Tutorial: Part 1/2

    转自:http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 Upda ...

  3. (转)苹果推送通知服务教程 Apple Push Notification Services Tutorial

    本文译自http://www.raywenderlich.com/.原文由iOS教程团队 Matthijs Hollemans 撰写,经原网站管理员授权本博翻译. 在iOS系统,考虑到手机电池电量,应 ...

  4. 远程通知APNs(Apple Push Notification Server)

    推送通知是由应用服务提供商发起的,通过苹果的APNs(Apple Push Notification Server)发送到应用客户端.下面是苹果官方关于推送通知的过程示意图: 推送通知的过程可以分为以 ...

  5. Provider Communication with Apple Push Notification Service

    This chapter describes the interfaces that providers use for communication with Apple Push Notificat ...

  6. (转)How to renew your Apple Push Notification Push SSL Certificate

    转自:https://blog.serverdensity.com/how-to-renew-your-apple-push-notification-push-ssl-certificate/ It ...

  7. (转)在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送

    在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送 From: http://saeapns.sinaapp.com/doc.html 1,在 ...

  8. 陌陌架构分享 – Apple Push Notification Service

    http://blog.latermoon.com/?p=878 先描述下基本概念,标准的iPhone应用是没有后台运行的,要实现实时推送消息到手机,需要借助Apple提供的APNS服务. iPhon ...

  9. Emojis support in Apple push notification

    I am working on iPhone app named "INTERSTIZIO".In this I have implemented functionality li ...

随机推荐

  1. Android Http请求失败解决方法

    1.MainActivity.java 文件中的onCreate方法改成如下: @SuppressLint("NewApi") @Override protected void o ...

  2. jQuery入门必须掌握的一些API

    jQuery 中文版文档:http://www.css88.com/jqapi-1.9/category/ajax/ jQuery入门,必须掌握以下的API,平时工作中经常会用到.未列出的API,在掌 ...

  3. 关于android:configChanges小结

    有段时间没更新博客了,做个音乐播放器遇到了坑,暂放来学习一个开源小项目

  4. osg三维重建的两种方法剖析:三角面片(osgUtil::DelaunayTriangulator)和四角面片(osg::HeightField) (2)

    // perform very basic sanity-check validation on a heightfield.bool validateHeightField(osg::HeightF ...

  5. jQuery extend方法介绍

    jQuery为开发插件提拱了两个方法,分别是: jQuery.fn.extend(object); jQuery.extend(object); jQuery.extend(object);为扩展jQ ...

  6. 2.2 文件 I/O 的基石:Path

    Path通常代表文件系统中的位置,能浏览任何类型的文件系统,包括zip归档文件系统: 文件系统中的几个概念:目录树.根目录.绝对路径.相对路径: NIO.2中的Path是一个抽象构造,你所创建和处理的 ...

  7. Java 的简单了解

    本文是主要根据百度百科以网上一些资料,整理的一点对Java的浅显的了解,不当之处,还请大家批评指正. 最初见到Java这个单词,是在以前的手机上,游戏启动时总会显示java的图标和名字,就感觉java ...

  8. 转 jQuery(图片、相册)插件代码实例

    jQuery想必大部分前端er都知道甚至很熟悉了,网上有数以万计的优秀的jQuery插件以及教程,今天收集了一些关于图片.相册的jQuery插件代码,希望会对你有所帮助. 1. 3D Gallery ...

  9. jsp语法与标签

    语法: <% 多行java代码 %> 在一个JSP页面中可以有多个脚本片断,在两个或多个脚本片断之间可以嵌入文本.HTML标记和其他JSP元素. 举例: <% int x = 10; ...

  10. IOS之动画

    IOS之动画   15.1 动画介绍 15.2 Core Animation基础 15.3 隐式动画 15.4 显式动画 15.5 关键帧显式动画 15.6 UIView级别动画 15.1 动画介绍 ...