Enabling Push Notifications Part 2 of 3

Enabling Push Notifications Part 2 of 3

This document is intended for the average Titanium Developer to enable push notifications.  It is assumed that the reader already has a basic knowledge of Titanium and the APIs.

Today we will talk about Part 2 of 3 of Push Notifications, which begins with Google App Registration.

Register your application with Google

Android Setup

  1. Create a Google API Project

  2. Register with Appcelerator Cloud Services

Step 1 : Create a Google API Project

Screen Shot 2014-02-27 at 4.28.18 PM.png

You will need to open the Google Developers Console by visiting https://cloud.google.com/console. From there you will need to sign in with your Google ID that you want associated with this project.  Once signed in you will see a basic screen and a big red button that says ‘CREATE PROJECT’.

Enter a Project Name, and ignore Project ID.  Project ID is randomly generated by Google to avoid duplication of IDs.  Click the ‘Create’ button and the Google Developer.

Console should refresh.  Now you should be on the projects Overview page.  At the top of this page you will see Project ID and Project Number.

Screen Shot 2014-02-27 at 4.16.34 PM.png

Copy the Project Number, since this will be used at a later point as the GCM Sender ID.  On the left corner of the page there is an APIs & Auth section.  Go to that page and a list of API items will populate.  Turn On the Google Cloud Messaging for Android.

Again under APIs & Auth you will see ‘Credentials’, click there.  Now you will see a section called ‘Public API Access’.  Click the ‘CREATE NEW KEY’ button to generate an API Access Key.

A popup will appear, on that select ‘Server Key’.  Another popup will appear asking you to enter IP Addresses in the text field, just click ‘Create’.

DO NOT ENTER ANY IP ADDRESSES

Now under the Public API access section there is a section for API key with a rather strange combination of letters & numbers.  Copy that text and hang onto it.  Now go to the Appcelerator Dashboard https://dashboard.appcelerator.com/.

As before select the app you are working with and click the ‘Cloud’ tab.  On the left menu click ‘Settings & Configurations’.  Then on the tabbed menu click ‘Android Push’.  It will ask you for the GCM API Key and GCM Sender ID, which you should have saved.  Enter those values in and click ‘Save Changes’.

Implement the code into a Common JS library

Ensure that you are using a Common JS library for notifications.  Create a ‘notifications.js’ file inside the ‘lib’ folder.  If the folder does not exists then create it.

iOS Code Setup

With iOS you must use Ti.Network.registerForPushNotifications the first time the user enters the application.  After registering with the server, the function should return a device token.  Save this device token in app properties.

Example : Ti.App.Properties.setString(‘deviceToken’, e.deviceToken);

However make sure you set the application properties on the callback and not inside the common JS library.  These lib files can sometimes act strangely when it comes to saving app properties.

index.js

//require the notifications common js lib file
var notifications = require('notifications');
//check for a device token
var deviceToken = Ti.App.Properties.getString('deviceToken');

//check to see if deviceToken exists
if(deviceToken === '') {
	//create a device token by registering for notifications
	deviceToken = notifications.register();
	//set the deviceToken app property
	Ti.App.Properties.setString('deviceToken', deviceToken);
}
//open the index window
$.index.open();

//controller
var mainWindow = Alloy.createController('Main').getView();
//open the mainWindow
mainWindow.open();

notifications.js

//require ti.cloud for iOS Notifications
var Cloud = require('ti.cloud');

//register the device and receive a token
exports.register = function() {
    Ti.Network.registerForPushNotifications({
        // Specifies which notifications to receive
        types: [
            Ti.Network.NOTIFICATION_TYPE_BADGE,
            Ti.Network.NOTIFICATION_TYPE_ALERT,
            Ti.Network.NOTIFICATION_TYPE_SOUND
        ],
        success: deviceTokenSuccess,
        error: deviceTokenError,
        callback: receivePush
    });
    // Process incoming push notifications
    function receivePush(e) {
        alert('Received push: ' + JSON.stringify(e));
    }
    // Save the device token for subsequent API calls
    function deviceTokenSuccess(e) {
        return e.deviceToken;
    }
    // Display an error upon failure to register
    function deviceTokenError(e) {
        alert('Failed to register for push notifications! ' + e.error);
    }
};

The device token that is generated will allow the application to receive notifications.  You will be able to register the device with ‘Channels’.   The server can push information to certain Channels.  Say you want sports news updates.  Then a Channel called ‘sports_updates’ could be created.  Channels are not done on the server side.  Creation is done on the user side.  There is not a way to manually add a channel on the ACS Dashboard.  Once a user subscribes to a channel for the first time then it is created.


//subscribe to a specific channel
exports.subscribe = function(channel, token) {
    Cloud.PushNotifications.subscribeToken({
        device_token: token,
        channel: channel
    }, function (e) {
        if (e.success) {
            alert('Subscribed');
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

Subscribing a device token to a channel is a function in the common JS library you created for Push Notifications.  In this function we pass two variables. One being the channel and the other being the device token that was generated earlier.  Each one is needed for the subscription.


//unsubsribe from a specific channel
exports.unsubscribe = function(channel, token) {
    Cloud.PushNotifications.unsubscribeToken({
        device_token: token,
        channel: channel,
    }, function (e) {
        if (e.success) {
            alert('Unsubscribed');
        } else {
            alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

You will also need to allow the user to unsubscribe from Channel based Pushed Notifications, which can be done using the unsubscribe function.

Main.js

//device token
var deviceToken = Ti.App.Properties.getString('deviceToken');
//require notificiations lib file
var notifications = require('notifications');
//create view to house label and buttons
var container = Ti.UI.createView({
	width           : Ti.UI.FILL,
	height          : Ti.UI.FILL,
	top             : 30,
	layout          : 'vertical',
	backgroundColor : '#FFFFFF'
});
//create label for title
var channelLabel = Ti.UI.createLabel({
	width     : Ti.UI.FILL,
	height    : Ti.UI.SIZE,
	text      : 'Select a Channel',
	textAlign : 'center'
});
//create sports channel button
var sportsButton = Ti.UI.createButton({
	width     : Ti.UI.FILL,
	height    : Ti.UI.SIZE,
	top       : 10,
	title     : 'Sports'
});
//sports button event listener
sportsButton.addEventListener('click', function(e){
	if(deviceToken !== '') {
		notifications.subscribe('sports_updates', deviceToken);
	} else {
		alert('Error, device not registered for Push Notifications');
	}
});
//add elements together
container.add(channelLabel);
container.add(sportsButton);
$.win.add(container);

Now we need to create a sample page to test this all out with.  It will have a view, label, and button.  Clicking this button will subscribe the user to sports updates from the ACS server.

This will create a basic view with a label and button on top of the window.  It will say ‘Sports’ and upon click will call the register function from the notifications lib file.

notifications.js Again


exports.userLogin = function() {
    // Log in to ACS
    Cloud.Users.login({
        login: 'push_notifications',
        password: 'pushy'
    }, function (e) {
        if (e.success) {
            alert('Login successful');
        } else {
            alert('Error:\n' +
                ((e.error && e.message) || JSON.stringify(e)));
        }
    });
};

You can also have users set up on the ACS server and log them in and subscribe to channels.  However the user account must exist.  Generally one user is created for the public, such as the ‘push_notifications’ user we see in the code.   This is perfect for just a basic app with notifications.  If you want user sessions and give the ability for people to create their own accounts you will have to look into Titanium.Cloud.Users on the documentation.

 

Try it and leave a comment below to let us know if you had any problems following these steps.

We will continue next week with part 3.

Enabling Push Notifications Part 1 of 3

Enabling Push Notifications Part 1 of 3

This document is intended for the average Titanium Developer to enable push notification.  It is assumed that the reader already has a basic knowledge of Titanium and the APIs.

There are several steps that you will need to follow to enable Push Notifications in your applications, they are :

  1. Determine which platform you wish to have notifications on.  Preferably on both iOS and Android.

  2. Set up your application in Appcelerator Studio.

  3. Become familiar with the Cloud section of the Dashboard.

  4. Register your application with Apple and create all necessary Application Identifiers, Certificates and Provisioning Profiles.

  5. Register your application with Google and set up the Google Developer Console for Google Cloud Services

  6. Implement the code into your application inside a Common JS library.

  7. Sending Notifications

Determine which platform you wish you have notifications on

The purpose of Titanium is to write one code base that works with multiple platforms.  This document will teach you how to set up for both of them.  However if you only wish to set up for one platform this document will help you do that as well.  The two platforms that will be discussed are iOS and Android.  First we will cover iOS setup and then Android.

Set up your application in Appcelerator Studio

You may already have your application created, or you may be starting from scratch.  Either way open your project in Appcelerator Studio.  Make sure that your application is set up for Appcelerator Services.  

You can enable this in two places.  First upon creation of the project.  Second is from the tiapp.xml file.  Open the tiapp.xml and you will see a section called ‘Appcelerator Services’.  Click the ‘Enable Appcelerator Services’, then turn on the ‘Cloud’ section.  Enabling cloud services in Studio creates a new Cloud application and adds its URL and credentials to the Titanium project.

Then you will see a section called ‘Modules’, this is where new modules can be added.  We are going to add the Cloud module (iOS) and the Cloud Push module (Android).

Click the ‘Plus’ icon and you will see this screen.  It gives you a list of modules that are available with the current SDK you have installed.  For this document we are working on 3.2.1.GA.  If you want notifications for iOS add the ti.cloud module.  Android you will need to add ti.cloudpush, or add both of them.

Become familiar with the Cloud Section of the Dashboard

Go to the Dashboard at https://dashboard.appcelerator.com/ and enter your Username and Password.  

There you will see a bar on top which is the main navigation.  Click the ‘Apps’ tab to show a list of apps that you have registered with Appcelerator.  Select the app you want to enable push notifications for.  Then click the ‘Cloud’ tab, which will load the ACS page.  

Screen Shot 2014-02-27 at 4.31.48 PM.png

Note:  There are two forms of Cloud Functionality on this Dashboard.  Select either Development or Production.  If you start with Development make sure you add what you need into Production when you want to distribute the app to either Apple or Google.

Register your application with Apple

iOS Setup

  1. Create an App Identifier
  2. Create a Push Notifications Certificate
  3. Create a Provisioning Profile
  4. Register Certificate with Appcelerator Cloud Services

Step 1:  Create an App Identifier

Apple requires you to register your application’s id and create a special certificate to be able to utilize push notifications.  You will need to login to the Apple Developer Member Center.  Once there you will see a section that looks similar to the one pictured below.

Select ‘Certificates, Identifiers & Profiles’ from this page.  Once there select the ‘Identifiers’ folder.  Click the + icon on the top right of the page to add a new Identifier.  Fill out the form below with the information required.  Under the ‘App Services’ section there is a column of checkboxes.  Select ‘Push Notifications’ and click ‘Continue’, then ‘Submit’, then ‘Done’.

Screen Shot 2014-02-27 at 2.19.19 PM.png  Note : You cannot use a Wildcard App ID for an app with Push Notifications

Step 2 : Create a Push Notifications Certificate

Go to the Certificates, Identifiers & Profilers.  On this page you will need to click the Certificates folder Icon.  That will load a screen that lists any certificates that you currently have created.  We need a Push Notification certificate so click the + button on the top right.

You will then come to a page asking you “What type of certification do you need?”  There are two sections for this called Development or Production.  You must decide which kind of certificate you need at this point.  Under each section there is a choice called “Apple Push Notification service SSL” .The Development version is just for testing and such.  Production will be what you need to send the app to Apple and make it public.

Then you will be asked to create a CSR (Certificate Signing Request).  The instructions to do this are listing on the page itself.  Follow the instructions and when complete click ‘Continue’.

Now you will need to upload that CSR file.  Click ‘Choose File’ and locate the CSR, which has an extension of ‘.certSigningRequest’.  Once selected click ‘Generate’

The certificate will be generated and available for you to download.  Save it somewhere on your computer.  Then open Keychain Access on your computer by either double clicking the Certificate or going to Applications – Keychain Access.  Locate the certificate inside Keychain by choosing ‘Certificates’ under the Category section.  Find the certificate in that list and right-click/two finger click it.  Choose ‘Export’ and you will be prompted to save a .p12 file.  Save it to your computer and open your web browser.  Go back to the Dashboard and select the ‘Cloud’ tab to continue Push Notification setup.

Choose ‘Settings & Configuration’ and a new page will load containing a tabbed view on it.  Select ‘iOS Push’ and you will see a section called ‘Push Certificate’ and an button to add a file. Click that button and find your .p12 file on your computer.  Upload the .p12 file and that will allow Appcelerator Cloud Services to communicate with Apple for Push Notifications.  If you set a certificate password you must also enter that as well.

Step 3 : Create a Provisioning Profile

Enabling Push Notifications

Go back to the Apple Developer Member Center and click ‘Certificates, Identifiers & Profiles’.  Click the + button on the top right of the page.

Screen Shot 2014-02-27 at 2.38.31 PM.png

Then you will need to select what type of profile you need.  There are two sections, Development and Distribution.  Select the most appropriate one for your project at this time and click ‘Continue’.

Screen Shot 2014-02-27 at 2.40.44 PM.png

Choose your applications id (the app identifier you created earlier) from the drop down list and click ‘Continue’.Screen Shot 2014-02-27 at 2.48.21 PM.png

Select your certificate that you created and click ‘Continue’.

Screen Shot 2014-02-27 at 2.49.21 PM.png

Now you can choose which devices you want to run the app on.  You can pick and choose or just select all.Screen Shot 2014-02-27 at 2.50.14 PM.png

Now you will need to name the profile.  Then click ‘Generate’ and download it.  It will save as a ‘.mobileprovision’ file.  Double-click that file to install it into Xcode.

Try it and leave a comment below to let us know if you had any problems following these steps.

We will continue next week with part 2 and the following with part 3.