- I am hoping that you have registered your app to Appcelerator Cloud services and also have the ACS key for both development and production.
- Add Cloud module for both iOS and android, and also add CloudPush module for android from Appcelerator IDE.
Step 1: Add the following line in your tixml.app file
Step 2: To send the push notification to the device, we require unique identifier of each device which is called device token in appcelerator/titanium. Device token in iOS is 128 bit long whereas in android it is max 256 bit ( its a combination of UDID of device and the ACS Key). So for a single device you will have 2 device tokens, one for development and other one for production as we have two different ACS Keys.
Code to get the device token for android device:
Titanium cloud push module provides retrieveDeviceToken() method to get the device token for android devices.
In the code above, on line 3 we are calling the retrieveDeviceToken() method and providing the callbacks for success and error.
On line 9 we have defined the method deviceTokenSuccess(). In this function we are saving the device token to app properties.
On line 10 we are calling subscribeToToken() function and which is taking two parameters device token and device type, which we will discuss later.
The code below is to get the device token for iOS device. On line 1 we are checking for iOS version, if iOS version is greater than 8, then lines 2-13 will execute otherwise the else part will execute (15-18).
Step 3: Subscribing to Push Notification for a channel using Device Token
After getting the device token, you must write the code below for subscribing the device to push notification for a channel.
In the below code subscribeToken API requires device token, channel name, type as parameters.
We can subscribe a device to multiple channels based on app requirements or we can subscribe a device to “ALL” channel.
Step 4: Get the callback on Notification click.
I have found many programmers struggling to get the callback on notification click for both Android and iOS. I have found a way to do so.
In step 2, while getting the device token, function receivePush on line 8 and18 for ios and line 17 for android will always get triggered whenever
- Any new notification is received and app is in foreground.
- User clicks on the notification to open the app.
In most of the cases people want a callback whenever app opens on notification click, so we need to distinguish the above two cases.
We can create a global flag and name it as “isPNClicked” and set it to “true” in receivePush method. We also need to reset it to “false” whenever app goes to background.
You can write the below code in callback
Now, whenever app gets resumed and if isPNClicked is “true” thats means app has been opened on notification clicked.
To verify this, write the code below on index.js file
Hope these examples have helped whoever wants to implement push notification using Titanium.