Home > Articles > Home & Office Computing > Entertainment/Gaming/Gadgets

Accessing iPhone's GPS, Acceleration, and Other Native Functions with QuickConnect

  • Print
  • + Share This
Lee Barney explains how to use GPS, Acceleration, and other native iPhone functionalities with the QuickConnect JavaScript API. He also shows the Objective-C code underlying the QuickConnect JavaScript Library.
This chapter is from the book

The iPhone has many unique capabilities that you can use in your applications. These capabilities include vibrating the phone, playing system sounds, accessing the accelerometer, and using GPS location information. It is also possible to write debug messages to the Xcode console when you write your application. Accessing these capabilities is not limited to Objective-C applications. Your hybrid applications can do these things from within JavaScript. The first section of this chapter explains how to use these and other native iPhone functionalities with the QuickConnect JavaScript API. The second section shows the Objective-C code underlying the QuickConnect JavaScript Library.

Section 1: JavaScript Device Activation

The iPhone is a game-changing device. One reason for this is that access to hardware such as the accelerometer that is available to people creating applications. These native iPhone functions enable you to create innovative applications. You decide how your application should react to a change in the acceleration or GPS location. You decide when the phone vibrates or plays some sort of audio.

The QuickConnectiPhone com.js file has a function that enables you to access this behavior in a simple, easy-to-use manner. The makeCall function is used in your application to make requests of the phone. To use makeCall, you need to pass two parameters. The first is a command string and the second is a string version of any parameters that might be needed to execute the command. Table 4.1 lists each standard command, the parameters required for it, and the behavior of the phone when it acts on the command.

Table 4.1. MakeCall Commands API

Command String

Message String

Behavior

logMessage

Any information to be logged in the Xcode terminal.

The message appears in the Xcode terminal when the code runs.

rec

A JSON string of a JavaScript array containing the name of the audio file to create as the first element. The second element of the array is either start or stop depending on if your desire is to start or stop recording audio data.

A caf audio file with the name defined in the message string is created.

play

A JSON string of a JavaScript array containing the name of the audio file to be played as the first element. The second element of the array is either start or stop depending on if your desire is to start or stop playing the audio file.

The caf audio file, if it exists, is played through the speakers of the device or the headphones.

loc

None

The Core Location behavior of the device is triggered and the latitude, longitude, and altitude information are passed back to your JavaScript application.

playSound

-1

The device vibrates.

playSound

0

The laser audio file is played.

showDate

DateTime

The native date and time picker is displayed.

showDate

Date

The native date picker is displayed.

The DeviceCatalog sample application includes a Vibrate button, which when clicked, causes the phone to shake. The button's onclick event handler function is called vibrateDevice and is seen in the following example. This function calls the makeCall function and passes the playSound command with –1 passed as the additional parameter. This call causes the phone to vibrate. It uses the playSound command because the iPhone treats vibrations and short system sounds as sounds.

function vibrateDevice(event)
{
    //the -1 indicator causes the phone to vibrate
    makeCall("playSound", -1);
}

Because vibration and system sounds are treated the same playing a system sound is almost identical to vibrating the phone. The Sound button's onclick event handler is called playSound. As you can see in the following code, the only difference between it and vibrateDevice is the second parameter.

If a 0 is passed as the second parameter, the laser.wav file included in the DeviceCatalog project's resources is played as a system sound. System sound audio files must be less than five seconds long or they cannot be played as sounds. Audio files longer than this are played using the play command, which is covered later in this section.

function playSound(event)
{
    //the 0 indicator causes the phone to play the laser sound
    makeCall("playSound", 0);
}

The makeCall function used in the previous code exists completely in JavaScript and can be seen in the following code. The makeCall function consists of two portions. The first queues up the message if it cannot be sent immediately. The second sends the message to underlying Objective-C code for handling. The method used to pass the message is to change the window.location property to a nonexistent URL, call, with both parameters passed to the function as parameters of the URL.

function makeCall(command, dataString){
    var messageString = "cmd="+command+"&msg="+dataString;
    if(storeMessage || !canSend){
        messages.push(messageString);
    }
    else{
        storeMessage = true;
        window.location = "call?"+messageString;
    }
}

Setting the URL in this way causes a message, including the URL and its parameters, to be sent to an Objective-C component that is part of the underlying QuickConnectiPhone framework. This Objective-C component is designed to terminate the loading of the new page and pass the command and the message it was sent to the framework's command-handling code. To see how this is done, see Section 2.

The playSound and the logMessage, rec, and play commands are unidirectional, which means that communication from JavaScript to Objective-C with no data expected back occurs. The remaining unidirectional standard commands all cause data to be sent from the Objective-C components back to JavaScript.

The passing of data back to JavaScript is handled in two ways. An example of the first is used to transfer acceleration information in the x, y, and z coordinates by a call to the handleRequest JavaScript function, described in Chapter 2, "JavaScript Modularity and iPhone Applications." The call uses the accel command and the x, y, and z coordinates being passed as a JavaScript object from the Objective-C components of the framework.

The mappings.js file indicates that the accel command is mapped to the displayAccelerationVCF function, as shown in the following line.

mapCommandToVCF('accel', displayAccelerationVCF);

This causes displayAccelerationVCF to be called each time the accelerometers detect motion. This function is responsible for handling all acceleration events. In the DeviceCatalog example application, the function simply inserts the x, y, and z acceleration values into an HTML div. You should change this function to use these values for your application.

The second way to send data back to JavaScript uses a call to the handleJSONRequest JavaScript function. It works much like the handleRequest function described in Chapter 2, but expects a JSON string as its second parameter. This function is a façade for the handleRequest function. As shown in the following code, it simply converts the JSON string that is its second parameter into a JavaScript object and passes the command and the new object to the handleRequest method. This method of data transfer is used to reply to a GPS location request initiated by a makeCall("loc") call and the request to show a date and time picker.

function handleJSONRequest(cmd, parametersString){
    var paramsArray = null;
    if(parametersString){
        var paramsArray = JSON.parse(parametersString);
    }
    handleRequest(cmd, paramsArray);
}

In both cases, the resulting data is converted to a JSON string and then passed to handleJSONRequest. For more information on JSON, see Appendix A, "Introduction to JSON."

Because JSON libraries are available in both JavaScript and Objective-C, JSON becomes a good way to pass complex information between the two languages in an application. A simple example of this is the onclick handlers for the starting and stopping of recording and playing back audio files.

The playRecording handler is typical of all handlers for the user interface buttons that activate device behaviors. As shown in the following example, it creates a JavaScript array, adds two values, converts the array to a JSON string, and then executes the makeCall function with the play command.

function playRecording(event)
{
    var params = new Array();
    params[0] = "recordedFile.caf";
    params[1] = "start";
    makeCall("play", JSON.stringify(params));
}

To stop playing a recording, a makeCall is also issued with the play command, as shown in the previous example, but instead of the second param being start, it is set to stop. The terminatePlaying function in the main.js file implements this behavior.

Starting and stopping the recording of an audio file is done in the same way as playRecording and terminatePlaying except that instead of the play command, rec is used. Making the implementation of the starting and stopping of these related capabilities similar makes it much easier for you to add these behaviors to your application.

As seen earlier in this section, some device behaviors, such as vibrate require communication only from the JavaScript to the Objective-C handlers. Others, such as retrieving the current GPS coordinates or the results of a picker, require communication in both directions. Figure 4.1 shows the DeviceCatalog application with GPS information.

Figure 4.1

Figure 4.1 The DeviceCatalog example application showing GPS information.

As with some of the unidirectional examples already examined, communication starts in the JavaScript of your application. The getGPSLocation function in the main.js file initiates the communication using the makeCall function. Notice that as in the earlier examples, makeCall returns nothing. makeCall uses an asynchronous communication protocol to communicate with the Objective-C side of the library even when the communication is bidirectional, so no return value is available.

function getGPSLocation(event)
{
    document.getElementById('locDisplay').innerText = '';
    makeCall("loc");
}

Because the communication is asynchronous, as AJAX is, a callback function needs to be created and called to receive the GPS informartion. In the QuickConnectiPhone framework, this is accomplished by creating a mapping in the mapping file that maps the command showLoc to a function:

mapCommandToVCF('showLoc', displayLocationVCF);

In this case, it is mapped to the displayLocationVCF view control function. This simple example function is used only to display the current GPS location in a div on the screen. Obviously, these values can also be used to compute distances to be stored in a database or to be sent to a server using the ServerAccessObject described in Chapter 8, "Remote Data Access."

function displayLocationVCF(data, paramArray){
    document.getElementById('locDisplay').innerText = 'latitude:
'+paramArray[0]+'\nlongitude: '+paramArray[1]+'\naltitude:
'+paramArray[2];
}

Displaying a picker, such as the standard date and time picker, and then displaying the selected results is similar to the previous example. This process also begins with a call from JavaScript to the device-handling code. In this case, the event handler function of the button is the showDateSelector function found in the main.js file.

function showDateSelector(event)
{
    makeCall("showDate", "DateTime");
}

As with the GPS example, a mapping is also needed. This mapping maps the showPickResults command to the displayPickerSelectionVCF view control function, as shown in the following:

mapCommandToVCF('showPickResults', displayPickerSelectionVCF);

The function to which the command is mapped inserts the results of the user's selection in a simple div, as shown in the following code. Obviously, this information can be used in many ways.

function displayPickerSelectionVCF(data, paramArray){
    document.getElementById('pickerResults').innerHTML = paramArray[0];

Some uses of makeCall, such as the earlier examples in this section, communicate unidirectionally from the JavaScript to the Objective-C device handlers. Those just examined use bidirectional communication to and from handlers. Another type of communication that is possible with the device is unidirectionally from the device to your JavaScript code. An example of this is accelerometer information use.

The Objective-C handler for acceleration events, see Section 2 to see the code, makes a JavaScript handleRequest call directly passing the accel command. The following accel command is mapped to the displayAccelerationVCF view control function.

mapCommandToVCF('accel', displayAccelerationVCF);

As with the other VCFs, this one inserts the acceleration values into a div.

function displayAccelerationVCF(data, param){
    document.getElementById('accelDisplay').innerText ='x:
'+param.x+'\ny: '+param.y+'\nz: '+param.z;
}

One difference between this function and the others is that instead of an array being passed, this function has an object passed as its param parameter. Section 2 shows how this object was created from information passed from the Objective-C acceleration event handler.

This section has shown you how to add some of the most commonly requested iPhone behaviors to your JavaScript-based application. Section 2 shows the Objective-C portions of the framework that support this capability.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020