How do I use Push Notifications with iOS?
You can download the sample stack from this url: https://tinyurl.com/y978y46k
Push Notifications allow you to send notifications from a server directly to an iOS device. This reduces network bandwidth for applications that may normally poll a server at intervals, in order to receive an update on information the user may be waiting for.
Although Push Notifications are convenient and reduce network traffic, they are not supported by every service, both on the server side and the application side.
In order to set up Push Notifications, it is necessary that the devices register with the server. The server needs information on what device the notification is to be sent to. The device also needs to be able to receive the notification and act upon it. This communication between the server and the device is encrypted and requires appropriate keys and certificates to be created.
This lesson is accompanied by a sample stack written by John Craig and uses the Json library by Mark Smith. The stack provides support for the certificate generation process and allows you to send Push Notifications from LiveCode. A demonstration on how to use the stack is provided by the author under the following YouTube link: http://www.youtube.com/watch?v=v7nR_aEAdKA.
Note: Button Send Notification PWD and the Password field were added to the original sample stack to allow integration into the original lesson. This additional functionality allows you to supply a Passphrase for the Private Key when sending a notification to the server.
This lesson is structured into the following six logical sections:
1. Generating the Certificates
2. Testing the Certificates
3. Creating the Push Notification Provisioning Profile
4. Writing a LiveCode Application with Push Notification Support
5. Sending a Push Notification
6. Trouble Shooting
Generating the Certificates
Push Notifications occur over encrypted communication and involve a sequence of handshakes between the Push Notification Server and the iOS device. The handshakes take place very much in the background when using the LiveCode syntax, but you have to create the certificates and keys that are used for the encrypted communication. The certificate and key generation process follows standard steps via Keychain Access and the Apple Provisioning Portal. More information on this process is available in the reference material of the Apple Provisioning Portal.
Creating a Certificate Signing Request
The first step is to create a Certificate Signing Request. Open the Keychain Access application on your Mac. This should be accessible under Applications/Utilities. Then select KeychainAccess -> Certificate Assistant -> Request a Certificate From a Certificate Authority... . This should launch the Certificate Assistant as is shown in this step.
Fill in your e-mail address and the common name you are using for the application that is to support Push Notifications.
Note: Each new application that supports Push Notifications needs its own Certificate Signing Request.
Once you have entered your e-mail address and the common name of the application, select the Save to disk radio button. Then select Continue. This allows you to save the Certificate Signing Request to your file system. In this example the certificate was saved as: PushNotificationApp.certSigningRequest
Note: Save the Certificate Signing Request into a common location for files that are specific to the application that is to support Push Notifications. Throughout this lesson, further certificates and keys are added to the same location.
Saving the Private Key
Once you have created the Certificate Signing Request for the Push Notification application, you can save the Private Key to your file system. Remain in the Keychain Access application and open the Keychain Access interface. Select login from the Keychains panel and Keys from the Category panel. The list window should now display the Keychain Keys. You should find a private key with the common name you provided when you created the Certificate Signing Request. Right click on the certificate and select Export "the common name". In this example the private key was saved as PushNotificationApp.p12. You need to enter a passphrase that protects the private key.
Creating the Application ID
Log into the iOS Provisioning portal and select App IDs from the left panel and Manage from the top tab. This should provide you with a window that is similar to the one shown in this step. Enter the common name for the application that is to support Push Notifications. Then select the Bundle Seed and the Bundle Identifier. The Bundle Identifier is usually written as the reverse of a domain name with the application name post fixed. This may be your domain name and your application name. In this example, we are using the name: com.runrev.PushNotificationApp. Then select Submit.
The Application ID
After selecting Submit, the screen is updated to reveal the Application ID. This is the Bundle Identifier you created, prefixed by an automatically generated code. Select the Configure link to ensure that the Application ID you created supports Push Notification.
Ensuring Push Notification is Supported
On the Configure Application ID page, ensure that the Enable for Apple Push Notification service tick box is selected. Then select Continue next to the kind of Push SSL Certificate you would like to use. In this lesson we are using the Development Push SSL Certificate for demonstration purposes. A final production application should use the Production Push SSL Certificate.
Certificate Signing Request Reminder
The first window to appear when configuring the Push SSL Certificate displays a reminder that a Certificate Signing Request has to be created before it is possible to proceed. This step was already completed before we signed into the iOS Provisioning portal. Select Continue.
Submitting the Certificate Signing Request
The Submit Certificate Signing Request page provides a Choose File button that allows you to upload the Certificate Signing Request you created at the beginning of this lesson. Press the button next to the text no file selected and select your Certificate Signing Request. This file should have the extension *.certSigningRequest. Next select the Generate button for your Apple Push Notification service SSL Certificate to be generated. The screen changes to display an activity indicator and text to indicate that the certificate is being generated. Once the certificate has been generated, the activity indicator disappears and text is updated to indicate that the certificate is available for you. Select Continue.
Downloading the Apple Push Notification service SSL Certificate
The dialog provides a Download button that allows you to download the certificate to your file system. The certificate name should look something like: aps_developer_identity.cer. Once you have downloaded the certificate, select Done. This completes the key certificate generation and we are ready to move on to the next stage.
Testing the Certificates
Now that you have created your certificates, you should test if they work. This step does not yet require you to implement a LiveCode application and can be executed from your Mac Terminal.
In order to run the test you first have to create a PEM file that contains both, the Apple Push Notification Service SSL Certificate and your Private Key. Once this PEM file is created, you can test whether or not the certificates work.
Creating your PEM file
In order to use the certificates you generated, you need to create a PEM file that stores both, your Apple Push Notification Service SSL Certificate and your Private Key. You can create the PEM file from a terminal.
Navigate to the directory that contains the certificates and key you generated earlier and execute the following steps. The file names here reflect the names of the certificates that were generated as part of this lesson. You have to update the syntax according the names you gave your certificates.
First create the application certificate PEM file. You can do this by double clicking on the aps_developer_identity.cer certificate file, then opening the Keychain Assistant and exporting the certificate as a p12 file and then converting it to a PEM file, in the same fashion as the PushNotificationApp.p12 is converted to a PEM file. Alternatively you can use a single command line that converts the aps_developer_identity.cer certificate file directly to a PEM file. Here we are opting for the single command line option, as follows:
openssl x509 -inform der -outform pem -in aps_developer_identity.cer -out PushNotificationAppCertificate.pem
Now create the application key PEM file as follows. You need to enter the import password and PEM pass phrase:
openssl pkcs12 -in PushNotificationApp.p12 -out PushNotificationAppKey.pem -nocerts
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
Now concatenate the two files:
cat PushNotificationAppCertificate.pem PushNotificationAppKey.pem > PushNotificationAppCertificateKey.pem
Talking to the Push Notification Server
Open a Mac terminal and execute the following line from the directory that contains the certificates you generated:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushNotificationAppCertificate.pem -key PushNotificationAppKey.pem
You are then asked to enter the pass phrase for the key you submitted:
Enter pass phrase for PushNotificationAppKey.pem:
If everything worked, then the server should send you a lot of information that may look something like the following:
depth=1 /C=US/O=Entrust, Inc./OU=www.entrust.net/rpa is incorporated by reference/OU=(c) 2009 Entrust, Inc./CN=Entrust Certification Authority - L1C
verify error:num=20:unable to get local issuer certificate
Key-Arg \ : None
Start Time: 1326899631
Timeout : 300 (sec)
Verify return code: 0 (ok)
At the end of this, you can enter some text and then select the return key. We entered the text "Hello World".
This completes the communication with the server and verifies that our certificates work.
Creating the Push Notification Provisioning Profile
Each application that supports Push Notifications requires its own Provisioning Profile. The following steps lead you through the process of creating the Provisioning Profile for your application.
Development Provisioning Profiles
Log into your iOS Provisioning Portal and select Provisioning on the left hand navigation panel and Development from the top tabs. You should see the Provisioning Profiles that are available to you. At the very least, you should see your general iOS Development Profile for app development. You now need to create a Provisioning Profile for the application that is to support Push Notification. Select the New Profile button.
Creating a new Development Provisioning Profile
You are presented with a blank form for a new Provisioning Profile. Fill in the name of the application under Profile Name. Tick who the certificate should apply to. From the drop down list, select the App ID for the application. This information should already be available in the drop down list. Then select the test devices on which the Provisioning Profile should operate. Once you have provided all of the required information, select Submit.
The new Push Notification Provisioning Profile
After you have created the new Push Notification Provisioning Profile, this profile may be in a Pending state. This state is only temporary and should change to Active within a few seconds. Try refreshing your browser to get the new states.
Downloading your Push Notification Provisioning Profile
The final step before you can add support for Push Notification to your application is to download the new Push Notification Profile and activate it on your Mac. In this example, the profile is called: Push_Notification_Application.mobileprovision. Double click on the profile, once it is downloaded, this makes it available for you to use.
Writing a LiveCode Application with Push Notification Support
Now that you have completed all of the work that is needed to support Push Notifications in LiveCode, it is time to implement code that acts upon a notification. Push Notifications are delivered by LiveCode in form of a message. Add the following or similar code to the stack card of your application:
on pushNotificationReceived pMessage answer "Push Notification Message:" && quote & pMessage & quote with "Okay" end pushNotificationReceived
Note: Look this message up in the dictionary and follow links to related dictionary entries.
Starting your Application
The first time you start your Push Notification enabled LiveCode application you should get a message that is similar to the one shown here. The message only ever appears the first time the application is launched and does not appear again. This indicates that the iOS device is aware that the application can received Push Notifications and sets up the necessary parameters to allow notifications to be delivered to the application.
Disallowing Push Notifications
If the user switched off Push Notifications for the application, then a dialog is displayed when the application starts up. This indicates that Push Notifications have been disabled.
Configuring Push Notification Settings
The user can configure the Push Notification Settings by selecting: Settings -> Notifications from their iOS device. This allows them to toggle supported features.
Accessing the Device Identifier
The Device Identifier can be retrieved using the following LiveCode function:
mobileGetDeviceToken answer the result with "Okay"
The Device Identifier is submitted to the server when registering for Push Notifications and provides the means by which the iOS device is identified when the notification is sent from the server.
N.B- You don't get a deviceToken until after you get a Registered message. You can check this with the pushNotificationRegistered function
Sending a Push Notification (PHP)
Push Notifications are normally sent from a server, but we can simulate this action from a terminal. You can use the following code example as a template. Update the highlighted code section with code that is specific to your requirements and save it to a .php file. In this example we are calling the file: PushNotifications.php
<?php // Provide the Host Information. $tHost = 'gateway.sandbox.push.apple.com'; $tPort = 2195; // Provide the Certificate and Key Data. $tCert = 'PushNotificationAppCertificateKey.pem'; // Provide the Private Key Passphrase (alternatively you can keep this secrete // and enter the key manually on the terminal -> remove relevant line from code). // Replace XXXXX with your Passphrase $tPassphrase = 'XXXXX'; // Provide the Device Identifier (Ensure that the Identifier does not have spaces in it). // Replace this token with the token of the iOS device that is to receive the notification. $tToken = 'b3d7a96d5bfc73f96d5bfc73f96d5bfc73f7a06c3b0101296d5bfc73f38311b4'; // The message that is to appear on the dialog. $tAlert = 'You have a LiveCode APNS Message'; // The Badge Number for the Application Icon (integer >=0). $tBadge = 8; // Audible Notification Option. $tSound = 'default'; // The content that is returned by the LiveCode "pushNotificationReceived" message. $tPayload = 'APNS Message Handled by LiveCode'; // Create the message content that is to be sent to the device. $tBody['aps'] = array ( 'alert' => $tAlert, 'badge' => $tBadge, 'sound' => $tSound, ); $tBody ['payload'] = $tPayload; // Encode the body to JSON. $tBody = json_encode ($tBody); // Create the Socket Stream. $tContext = stream_context_create (); stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert); // Remove this line if you would like to enter the Private Key Passphrase manually. stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase); // Open the Connection to the APNS Server. $tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext); // Check if we were able to open a socket. if (!$tSocket) exit ("APNS Connection Failed: $error $errstr" . PHP_EOL); // Build the Binary Notification. $tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody; // Send the Notification to the Server. $tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg)); if ($tResult) echo 'Delivered Message to APNS' . PHP_EOL; else echo 'Could not Deliver Message to APNS' . PHP_EOL; // Close the Connection to the Server. fclose ($tSocket); ?>
From a terminal execute your .php file using this syntax (replace the file name with the name you created for the code):
Sending a Push Notification (LiveCode)
You can send a Push Notification from LiveCode using the sample stack that John Craig provided. We are listing a modified version of his server call code here to provide a comparative algorithm to the PHP code that is shown in the previous step.
# Provide the Host Information. local tHost = "gateway.sandbox.push.apple.com" local tPort = 2195 # Provide the Certificate and Key Data. local tCert = "PushNotificationAppCertificateKey.pem" # Provide the Private Key Passphrase (alternatively you can keep this secrete and # enter the key manually on the terminal -> remove relevant line from code). # Replace XXXXX with your Passphrase local tPassphrase = "XXXXX"
# Provide the Device Identifier (Ensure that the Identifier does not have spaces in it). # Replace this token with the token of the iOS device that is to receive the notification. local tToken = "b3d7a96d5bfc73f96d5bfc73f96d5bfc73f7a06c3b0101296d5bfc73f38311b4" # The message that is to appear on the dialog. local tAlert = "You have a LiveCode APNS Message" # The Badge Number for the Application Icon (integer >=0). local tBadge = 8; # Audible Notification Option. local tSound = "default" # The content that is returned by the LiveCode "pushNotificationReceived" message. local tPayload = "APNS Message Handled by LiveCode" # The target folder. local tFolder = "/Users/none/PushNotifications" # Keep note of the current folder. local tSavedFolder put the defaultFolder into tSavedFolder set the defaultFolder to tFolder # Create the notification. local tBody put tAlert into tBody["aps"]["alert"] put tBadge into tBody["aps"]["badge"] put tSound into tBody["aps"]["sound"] put Payload into tBody["payload"] # Convert to json - Mark Smith's library. start using stack "libJson" local tNotification put arrayToJson(tBody) into tNotification # Build the binary notification to send. local tBinary put empty into tBinary repeat for each item tCode in "0,0,32" put numToChar(tCode) after tBinary end repeat put binaryEncode("H*", tToken) after tBinary put binaryEncode("n", length(tNotification)) after tBinary put tNotification after tBinary # Write the binary to a file and send via openssl put tBinary into URL("binfile:Notification.bin") get shell("cat Notification.bin | openssl s_client -connect" && tHost & ":" & \ tPort && "-cert" && tCert && "-pass pass:" & tPassphrase) answer "Result after attempting to send notification to server:" & LF & LF & it set the defaultFolder to tSavedFolder
The following steps list some of the issues that were encountered when writing this lesson.
Could not Validate that the Certificates Work
If it was not possible to validate that the certificates work, then it is possible that you do not have access to the Push Notification Server.
Open a Mac terminal and enter the following line:
ping -c 5 gateway.sandbox.push.apple.com
You should get the following or similar response:
PING gateway.sandbox.push-apple.com.akadns.net (188.8.131.52): 56 data bytes Request timeout for icmp_seq 0 Request timeout for icmp_seq 1 Request timeout for icmp_seq 2 Request timeout for icmp_seq 3
If you do not get the above response, then it is possible that you do not have internet access or a firewall is blocking your access to that server.
If you do get this response, then it is possible that your certificates are not correct. Try debugging the process that you used to created the certificates.
Unable to get Local Issuer Certificate
You may get a verify error:num=20:unable to get local issuer certificate message when trying to talk to the Push Notification Server. This is possibly the case if the Push Notification Server does not send the client certificates in the Acceptable Certificate Authority List. This message on its own does not indicated a problem with the implementation of LiveCode Push Notification Certificates.
You should find that the following command from a Mac terminal also produces the error message:
openssl s_client -showcerts -connect gateway.sandbox.push.apple.com:2195
Push Notification does not seem to be Supported on my App
If you try your application, but you do not appear to have support for Push Notifications enabled, then this may be because the Provisioning Portal has not yet enabled the Certificate for your application. This problem has also been reported by a number of other developers.
A recommended solution is to touch or force an update to the Push SSL Certificate for the application. You can do this by logging into the Provisioning Portal and navigate to the page shown here. Then unselect the Enable for Apple Push Notification service tick box and select it again. Then select Done. You are effectively not making any changes to the Certificate, but the update appears all that is needed for the Certificate to be recognized.