Your message has been sent.
This article has been saved to your account.
Go to my account
This article has been emailed to your Kindle.
Send this article
Complete the form below to send this article, iPhone: Issues Related to Calls, SMS, and Contacts, to a friend (or to yourself). We will never share your details (or your friend's) with anyone. For more information, read our Privacy Policy.
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
| 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.
- 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> - 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> - 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:

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...
- 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> - 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...
- The first step is to create a new PhoneGap project through Xcode.
- 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> - 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>");
} - 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:

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

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

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.
| 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...
- 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.
- 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> - 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");
} - 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> - 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:

- 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:

- 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:

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...
- 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> - 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.
- 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> - When you're ready, load the new application for getting the main screen as shown in the following screenshot:

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

- 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:

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: Installing Frameworks [article]
- A Guide to Understanding Core Data iOS [article]
- Cocos2d for iPhone: Surfing Through Scenes [article]
- Core Data iOS: Designing a Data Model and Building Data Objects [article]
- Cocos2d for iPhone: Adding Layers and Making a Simple Pause Screen [article]
- Cocos2d for iPhone: Handling Accelerometer Input and Detecting Collisions [article]
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.



Post new comment