Displaying local notifications on the iPhone

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.

Note

Complete source code for this recipe can be found in the /Chapter 8/Recipe 5 folder.

How to do it…

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)!

How to do it…

How it works…

A local notification consists of a number of parameters, including:

  • alertBody: The message that appears in your alert dialog
  • alertAction: The right-hand button that executes your application
  • userInfo: The data you wish to pass back to your app
  • date: When to execute the notification

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.152