iPhone: Issues Related to Calls, SMS, and Contacts

Exclusive offer: get 50% off this eBook here
iPhone JavaScript Cookbook

iPhone JavaScript Cookbook — Save 50%

Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa

$26.99    $13.50
by Arturo Fernandez Montoro | June 2011 | Web Services Web Graphics & Video

Undoubtedly, iPhone is one of the most exciting mobile devices in the world. Its iOS is used in other Apple devices, such as iPad and iPod Touch.

Although iPhone is a smartphone, we shouldn't forget its main functionality of making phone calls and sending text messages in addition to its other rich features. This article by Arturo Fernandez Montoro, author of iPhone JavaScript Cookbook, will teach you how to use the contacts stored in the internal address book of the device.

Specifically, we will cover:

  • Calling a number
  • Sending an SMS to a number
  • Selecting contacts
  • Creating a new contact
  • Searching and displaying contacts

 

iPhone JavaScript Cookbook

iPhone JavaScript Cookbook

Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa

        Read more about this book      

(For more resources related to this subject, see here.)

At the time of publication, working with contacts requires us to develop native applications. But we can use JavaScript with the PhoneGap framework for building these kinds of applications for the iPhone. This is the main reason for applying this framework for the recipes included in this article.

This article focuses on issues related to calls, SMS, and contacts. We'll learn how to handle contacts and how to send an SMS or place a phone call simply by interacting with the user interface.

Calling a number

In this recipe, you'll learn how to call a number when a user clicks on a button in the user interface. Specifically, we're going to build a simple list containing our contacts where each represents a person and their phone number. After clicking on one of these elements the dial screen will be opened and the user will only need to click on the green button for calling the specified number.

We only need to build a simple XHTML file for this recipe. It can be found at code/ch08/call.html in the code bundle provided on the Packtpub site.

Code files can be downloaded at the Packt website.

Getting ready

This recipe requires the use of the iWebKit framework.

How to do it...

Open your favorite text editor or IDE and create a new file called call.html.

  1. Add the standard XHTML headers and the required lines for invoking the JavaScript and CSS files provided by iWebKit:

    <link href="../iwebkit/css/style.css" rel="stylesheet
    media="screen" type="text/css" />
    <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="../iwebkit/javascript/functions.js"
    type="text/javascript"></script>

  2. Add the main HTML code for defining our user interface:

    <body class="list">
    <div id="topbar">
    <div id="title">Call</div>
    </div>
    <div id="content">
    <ul>
    <li class="title">Contacts</li>
    <li><a class="noeffect" href="tel:555-666-777">
    <span class="name">Aaron Stone</span></a></li>
    <li><a class="noeffect" href="tel:555-888-999">
    <span class="name">Ben Jackson</span></a></li>
    <li><a class="noeffect" href="tel:555-222-333">
    <span class="name">Bob McKenzie</span></a></li>
    <li><a class="noeffect" href="tel:555-444-666">
    <span class="name">Luke Johnson</span></a></li>
    <li><a class="noeffect" href="tel:555-333-666">
    <span class="name">Michael Sterling</span></a></li>
    </ul>
    </div>

  3. Now, save your new file and load it on your device. The following screenshot shows you the result of loading the file built for this recipe:

    iPhone: Issues Related to Calls, SMS, and Contacts

How it works...

The most important part of the code in this recipe is the anchor element inside each <li> tag. The href attribute of the anchor element is using a string, which represents a specific protocol followed by a number. In fact, tel identifies the protocol and the iPhone, understanding its meaning displays the dial screen allowing the user to call a number. On the other hand, the class noeffect was applied to each anchor for opening the dial screen in fullscreen mode.

From a strict point of view, iWebkit is not a must for calling numbers. Safari Mobile indentifies the tel protocol by default. However, we used the mentioned framework because it helps us to easily construct a list with many items.

What happens if you are using an iOS device other than the iPhone? It is not possible to call numbers from an iPad or iPod touch as of now. The code developed for this recipe works differently in these devices. Instead of calling numbers, iPad and iPod touch will ask you if you want to save numbers in the address book.

Sending an SMS to a number

The previous recipe explained how you can call a number from your applications. This recipe will show you how to send an SMS to a selected number. For simplicity we're going to use the same approach. We'll develop a simple XHTML file displaying a list with different contacts. When the user clicks on one of the contacts the iPhone will display the screen for sending an SMS.

Getting ready

As in the previous recipe we will use the iWebKit framework. As both recipes are similar, we're going to use the same XHTML file developed for the previous recipe.

How to do it...

  1. Open the call.html file and replace the content of the href attribute of each <li>item for a new string starting with sms: instead of tel. For example, the first item will be the following:

    <li>
    <a class="noeffect" href="sms:555-666-777">
    <span class="name">Aaron Stone</span>
    </a>
    </li>

  2. Save the new content of the original file as a new file called sms.html, then you'll be ready for testing it on your iPhone.

How it works...

As you've learned in the previous recipe, Safari Mobile identifies the tel protocol for calling numbers. In the same way, sms is used for sending SMS's. Also for this recipe the iWebKit is used for building the user interface.

Selecting contacts

Thanks to this recipe we'll learn how to select a contact from the address book of the iPhone and to display its related information. Our goal is quite simple; when the user clicks on a button, a new screen will display all available contacts. After clicking on one of these elements, the complete name of the selected contact will be displayed in the main screen.

Although this recipe is very simple, you can apply it for building complex applications that require dealing with contacts available through the address book of the iPhone.

The complete code for this recipe can be reached at code/ch08/queryAddress in the code bundle provided on the Packtpub site.

Getting ready

For this recipe we'll use three different frameworks: PhoneGap, XUI, and UiUIKit. Before continuing, make sure you have these frameworks installed on your machine. Also, remember you'll need a Mac OS X computer with the iOS SDK and Xcode installed.

How to do it...

  1. The first step is to create a new PhoneGap project through Xcode.
  2. After creating your new project, the next step will be to open the main index.html file for adding our own code for this recipe. First, you should add the following lines inside the head section of the mentioned HTML file:

    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="xui-2.0.0..min.js"></script>
    <link rel="stylesheet" href="uiuikit/stylesheets/iphone.css" />
    <style type="text/css">
    #mybtn {
    margin-right: 12px;
    }
    </style>

  3. The next step is to comment out the JavaScript function preventBehavior() and the line below this function. Then, we're going to add our JavaScript code:

    function searchContact() {
    navigator.contacts.chooseContact(onSucessContact);
    }
    function onSucessContact(contact) {
    var selectedContact = contact.name;
    x$('#ul_contacts').html( 'inner', "<li>" + selectedContact +
    "</li>");
    }

  4. Finally, we'll modify the original body section adding the following lines of HTML code:

    <div id="header">
    <h1>Contacts</h1>
    </div>
    <h1>Working with contacts</h1>
    <p id="p_btn">
    <a href="#" id="mybtn" onclick="searchContact()"
    class="button white">Select</a>
    </p>
    <ul id='ul_contacts'></ul>

Before continuing and after applying all changes inside the code, we need to copy some files to the www directory of our project. Specifically, we're going to copy the uiuikit directory and the xui-2.0.0.min.js file. Remember, these components belong to the UiUIKit and XUI framework respectively.

Save your project and click on the Build and Run button of Xcode for testing your new application. After loading the application in the iPhone Simulator, you can see a screen similar to next screenshot:

iPhone: Issues Related to Calls, SMS, and Contacts

When the user clicks on the button Select, a list with all the available contacts will be displayed as shown in the following screenshot:

iPhone: Issues Related to Calls, SMS, and Contacts

After selecting one of the items showed in the list, our application will display the data for the selected contact:

iPhone: Issues Related to Calls, SMS, and Contacts

How it works...

PhoneGap provides a JavaScript function for accessing the predefined screen of the iPhone for selecting contacts. The name of this function is ChooseContact() and it is invoked through the navigator.contacts predefined object. It encapsulates the access to the address book of the iPhone. As a parameter, this function requires a callback method that will be invoked when a contact is selected. In our case, we implemented a function called onSuccessContact(), which captures the complete name of the contact displaying the result in a simple list. onSuccesContact uses a parameter called contact, which represents an object containing the information related to the selected contact from the address book.

The XUI framework allows us to add new items to our ul list by manipulating the DOM of the HTML page. On the other hand, the UiUIKit framework was used for building the user interface for our small application.

We used a bit of CSS for centering our button. Actually, we modified the right margin of this widget. The CSS style for this appears before the JavaScript code, also inside the head section.

iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa
Published: June 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources related to this subject, see here.)

Creating a new contact

The goal for this recipe will be to add a new contact inside the address book of the iPhone. We'll use a simple form with the basic data for a new contact: first name, last name, and phone number. The user can type this data inside the mentioned form. By clicking on a button the contact will be added. A simple alert box will notify this action to the user.

All code required for this recipe can be found at code/ch08/newContact in the code bundle provided on the Packtpub site.

Getting ready

Make sure you've installed PhoneGap and UiUIKit on your Mac computer.

How to do it...

  1. Our first task will be to create a new PhoneGap project using Xcode and the PhoneGap-based template. Edit the index.html file stored in the www folder. Before changing the code of this file, we need to copy the folder uiuikit from the UIUIKit framework inside the mentioned www folder of our new project.
  2. Comment out the JavaScript lines of the function called preventBehavior(). Then, add the following lines inside the head section and before the JavaScript code:

    <link rel="stylesheet" href="uiuikit/stylesheets/iphone.css" />
    <style type="text/css">
    #mybtn {
    margin-right: 12px;
    }
    </style>

  3. Now, it's time to add our own code inside the JavaScript section of index.html:

    function saveContact() {
    var dataContact = {'firstName':
    document.frm.first_name.value,
    'lastName':
    document.frm.last_name.value,
    'phoneNumber':
    document.frm.phone.value};
    navigator.contacts.newContact(dataContact, onSucessContact);
    }
    function onSucessContact(contact) {
    navigator.notification.alert('Contact created',
    'Contacts', "Done");
    }

  4. Finally, we'll add the required HTML lines for building the user interface for our application. The following code will be added inside the body section:

    <di v id="header">
    <h1>Contacts</h1>
    </div>
    <h1>New contact</h1>
    <form name="frm">
    <ul class="form">
    <li>
    <input type="text" name="first_name" value=""
    placeholder="First name" id="first_name"/>
    </li>
    <li>
    <input type="text" name="last_name" value=""
    placeholder="Last name" id="last_name"/>
    </li>
    <li>
    <input type="text" name="phone" value=""
    placeholder="Phone" id="phone"/>
    </li>
    </ul>
    </form>
    <p id="p_btn">
    <a href="#" id="mybtn" onclick="saveContact()"
    class="button white">Save</a>
    </p>

  5. For testing our new application we click on the Build and Run button of Xcode. After loading the application, the result will be similar to the following screenshot:

    iPhone: Issues Related to Calls, SMS, and Contacts

  6. If we type some text inside each element of the form and click on the Save button, the new contact will be added to our address book:

    iPhone: Issues Related to Calls, SMS, and Contacts

  7. You can check if the new contact was added. For taking this action, we can access our address book list and look for the new contact. You will see that it exists, and by clicking on it you'll see the information just added:

    iPhone: Issues Related to Calls, SMS, and Contacts

How it works...

The main JavaScript function used in this recipe is saveContact(). This function takes two actions: getting data from the form and encapsulating the call to the newContact() function provided by PhoneGap through the navigator.contacts object. As you can see, this method requires a dictionary with three main keys which represent the first name, second name, and phone number for the new contact. In this case, we're picking up these values directly from the form using the attribute value.

onSuccessContact() is a function working as callback, which displays a simple alert box using the predefined alert method of the navigator.notification object. This callback function will be invoked after saving the new contact inside the address book.

For building our form we used the UiUIKit framework, which provides a simple and consistent look and feel using a HTML form. Our button has an onclick handler for invoking the saveContact() function, which is enabled after clicking on it.

Finally, the functionality for displaying our new contact is provided directly with iOS, so we don't need to use any additional code.

Searching and displaying contacts

Sometimes it could be very interesting to build our own interface for searching contacts saved in the address book and for displaying the results. We'll build a simple form with a textbox where the user can type text. A button will be used for inputting the typed text and then we'll look for coincidences in our address book. The field chosen for our search will be the First name.

After finding contacts, we'll display a simple list with the results. When the user clicks on one of the items, the data for the selected contact will be displayed on a new page.

Getting ready

As with the other recipes in this article, we're going to use PhoneGap, UiUIKit, and XUI. Please, make sure you've installed these frameworks before continuing.

How to do it...

  1. As you've learned, create a new PhoneGap project in Xcode. Open the main index. html file and add the required lines for loading UiUIKit and XUI:

    <link rel="stylesheet" href="uiuikit/stylesheets/iphone.css" />
    <script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="xui-2.0.0.min.js"></script>

  2. Now, we need to add our own JavaScript code:

    function onError(contactError) {
    navigator.notification.alert('Error!', 'Error', 'Error');
    }
    function searchContacts() {
    var options = {};
    options.nameFilter = document.frm.first_name.value;
    navigator.contacts.getAllContacts(onSucessContact, onError,
    options);
    }
    function displayContact(contactID) {
    navigator.contacts.displayContact(contactID, null,
    {"allowsEditing": false});
    }
    function onSucessContact(contacts) {
    var options = {};
    options.allowsEditing = true;
    var contactsLen = contacts.length;
    var names = "";
    if (contactsLen <= 0)
    names = "<li>No contacts founded</li>";
    for (var i = 0; i < contactsLen; i++) {
    var firstName = contacts[i].firstName;
    var lastName = contacts[i].lastName;
    names += '<li class="arrow"><a href="#"
    onclick="displayContact(' + contacts[i].recordID + ');' +
    '">' + firstName + " " + lastName + "</a></li>";
    }
    x$('#ul_contacts').html( 'inner', names);
    }

    Don't forget to comment out the preventBehaviour(e) JavaScript function and th e line below it.

  3. The last step will be to build our user interface using a simple form and a Search button:

    <div i d="header">
    <h1>Contacts</h1>
    </div>
    <h1>Searching contacts</h1>
    <form name="frm">
    <ul class="form">
    <li>
    <input type="text" name="first_name" value=""
    placeholder="First name" id="first_name"/>
    </li>
    </ul>
    </form>
    <p id="p_btn">
    <a href="#" id="mybtn" onclick="searchContacts()"
    class="button white">Search</a></p>
    <ul id='ul_contacts'></ul>

  4. When you're ready, load the new application for getting the main screen as shown in the following screenshot:

    iPhone: Issues Related to Calls, SMS, and Contacts

  5. After typing a name inside the textbox and clicking on the Search button, a list with the result of the search will be displayed:

    iPhone: Issues Related to Calls, SMS, and Contacts

  6. When the user clicks on one of the items of the list, the data for the selected contact will be displayed on a new page:

    iPhone: Issues Related to Calls, SMS, and Contacts

How it works...

The user interface for this recipe is quite simple. We only need a form with a text input, a button for searching, and an unordered list for displaying results. UiUIKit provides all of these widgets, so we used this framework.

Our button is using a handler for calling the searchContact() JavaScript function, which will invoke the method getAllContacts() provided by the navigation.contacts object of PhoneGap. This method is using three parameters: two callback functions and one options dictionary for setting the field criteria for searching. One of the callbacks will be launched if something is wrong and the other if everything is fine. The mentioned options dictionary is using a predefined variable called nameFilteriable and its value is retrieved up from our text input.

onSuccessContact() received as a parameter an array, containing all the matching contacts from the search results. We're iterating over this array for getting the first and last name for each contact. Both of them are assigned to different JavaScript variables and are used for building items for our unordered list. Also, we're adding an onclick handler for each one, which will invoke the displayContact() function after clicking on it.

Inside our onSuccesContact() function we checked if results are found for displaying a specific message if we don't find contacts that match our query.

The displayContact() JavaScript function encapsulates the call to the function with the same name predefined inside the navigator.contacts object of PhoneGap. The responsibility of this function is to display all the data for the selected contact. As you can observe, we used an additional dictionary passed as a parameter to this function. Actually, the value false for allowsEditing() is set when we don't want the user to be able to change any value of our contact. Otherwise, you can set this property to true.

Finally, XUI allows us to create a list with different items at in runtime.

Summary

This article focused on issues related to calls, SMS, and contacts. We learnt how to handle contacts and how to send an SMS or place a phone call simply by interacting with the user interface.


Further resources on this subject:


iPhone JavaScript Cookbook Clear and practical recipes for building web applications using JavaScript and AJAX without having to learn Objective-C or Cocoa
Published: June 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Arturo Fernandez Montoro

Arturo Fernandez Montoro is a software architect specializing in design, development, testing, and deployment of high-traffic web applications.

Since 2002, he often writes for different Linux and Open Source printed and online magazines, such as Todo Linux, Linux+, Linux Magazine, and Free Software Magazine. Also, he has written the iPhone JavaScript Cookbook for Packt Publishing.

His professional experience includes technologies such as Django, Ruby on Rails, J2EE, PHP, web application servers, relational and NoSQL databases, JavaScript, HTML5, and CSS. He spent the last three years working as a software architect and a Python/Django lead developer.

Currently, Arturo lives in Madrid working as a software architect for QDQ Media, the biggest online marketing agency in Spain. He can be reached at arturo@bsnux.com.

Books From Packt


Core Data iOS Essentials
Core Data iOS Essentials

iPhone User Interface Cookbook: RAW
iPhone User Interface Cookbook: RAW

Cocos2d for iPhone 0.99 Beginner's Guide
Cocos2d for iPhone 0.99 Beginner's Guide

Xcode 4 iPhone Development Beginner's Guide
Xcode 4 iPhone Development Beginner's Guide

iPhone Applications Tune-Up: RAW
iPhone Applications Tune-Up: RAW

Flash Development for Android Cookbook
Flash Development for Android Cookbook

Android 3.0 Application Development Cookbook
Android 3.0 Application Development Cookbook

MeeGo 1.0 Mobile Application Development Cookbook
MeeGo 1.0 Mobile Application Development Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
h
b
H
3
F
F
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software