Another post iOS 4+ feature was the introduction of local notifications which allowed the developer to create basic notification alerts that looked and acted similar to Push notifications, but without the hassle of creating all of the certificates and server-side code necessary for Push to work. In this recipe, we are going to extend the previous code that we wrote for our background service, and create a local notification when the app is pushed to the background of the system.
Open your project's bg.js
file from the previous recipe, and extend it by adding in the following code:
var notification = Ti.App.iOS.scheduleLocalNotification({ alertBody: 'Hey, this is a local notification!', alertAction: "Answer it!", userInfo: {"Hello": "world"}, date: new Date(new Date().getTime()) });
Now in your app.js
file, create the following event listener and handler. It will execute whenever your Answer It confirmation button is pushed during the background process:
//listen for a local notification event Ti.App.iOS.addEventListener('notification', function(e) { Ti.API.info("Local notification received: "+ JSON.stringify(e)); alert('Your local notification caused this event to fire!'), });
When you are finished, run your application in the emulator to test it. You should be able to "background", or pause, the application after it starts running (by pressing the "home" button on your iPhone) and receive a local notification. Tapping on Answer It will reload your app and cause our "notification' event listener to fire (as seen in the following screenshots)!
A local notification consists of a number of parameters, including:
Our example is using the current date and time, meaning the notification will appear momentarily after the application has become "backgrounded". When the notification appears, the user can then either cancel it, or use our custom "action" button to re-launch the app and execute our "notification" event handler.
18.116.21.152