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, in this case the PushNotificationAppAssets folder.
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. Make sure you save this in the same folder where you saved the file PushNotificationApp.certSigningRequest. Also you need to enter a passphrase that protects the private key.
Creating the Application ID
Log into the iOS Provisioning portal and select Identifiers from the left panel. This should provide you with a window that is similar to the one shown in this step. Then click on the + button to create a new app identifier:
Choose App IDs and click on Continue button:
Enter the Description for the application that is to support Push Notifications. Then choose Explicit in the Bundle ID field and enter a bundle identifier. This 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.livecode.pushNotificationApp. Then scroll down and check "Push Notifications", and then click Continue.
You should see this screen:
The Application ID
After clicking on Register, the Bundle ID you just added is included in the list of the Identifiers. Click on com.livecode.pushNotificationApp to edit it:
Scroll down, find Push Notifications and click on Configure:
This dialog should appear:
Then select the kind of Push SSL Certificate you would like to create. In this lesson we are using the Development SSL Certificate for demonstration purposes. A final production application should use the Production SSL Certificate. Then you should see this screen:
In the Upload a Certificate Signing Request field, choose the file PushNotificationApp.certSigningRequest we created in the beginning of this lesson (which is saved in the PushNotificationAppAssets folder). Then click on Continue:
The certificate is now created. Click on the Download button, to download the certificate to your file system. The certificate name should look something like: aps_development.cer. Again, make sure you save this in the same folder where we have saved all the necessary files so far, that is PushNotificationAppAssets in this lesson. Once the certificate is saved, double click on it. This will add it to your Keychain.
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:
Then 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_development.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_development.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_development.cer -out PushNotificationAppCertificate.pem
Verify the file PushNotificationAppCertificate.pem is created in the folder PushNotificationAppAssets:
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
This should create a new file named PushNotificationAppCertificateKey.pem in the same folder:
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 Apple Dev Portal and select Profiles on the left hand navigation panel. Click on the + button:
Choose Development, and then iOS App Development and click Continue.
Creating a new Development Provisioning Profile
In the App ID dropdown, choose pushNotificationApp and click Continue:
In the next screen, tick all the certificates that you want to include in this provisioning profile. Make sure they are Development certificates, as this will be a Development provisioning profile. Then click Continue.
Then select the test devices on which the Provisioning Profile should operate. Once you have provided all of the required information, click Continue.
The new Push Notification Provisioning Profile
Finally, choose a name for this profile, and click Generate:
The new Development provisioning profile is now ready. Click on Download, and make sure you save it in the same folder (PushNotificationAppAssets). In this example, the profile is called: Panos_PushNotificationApp.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
on pushNotificationRegistered pToken answer "Registered for Push Notification:" && quote \ & pToken & quote with "Okay" end pushNotificationRegistered
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. You can use the following code with LiveCode 8.x and 9.x:
on mouseup # 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 = "XXXX" # 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 = "XXXX" # 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. Ensure this folder contains all the certificates and keys needed local tFolder = "/Users/panos/Documents/PushNotificationAppAssets" # 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 tPayload into tBody["payload"] 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 end mouseup
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 (220.127.116.11): 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 app ID has not all the necessary Certificates for Push Notifications. Go to Apple Dev Portal, choose the app identifier from the Identifiers section, and scroll down to Push Notifications. Click Edit.
In this example, we see that this app identifier has only a Development SSL certificate. So, this means that Push Notifications will only work in Development mode. If you want Push Notifications to work in a Production app, you need to follow the same steps as above for the generation of a Production SSL Certificate. Also you'll need to do all the previous steps again, but this time for Production instead of Development. Finally, in the sample code, you'll need to replace the host information from