Accessing iPhone's GPS, Acceleration, and Other Native Functions with QuickConnect
- Section 1: JavaScript Device Activation
- Section 2: Objective-C Device Activation
- Section 3: Objective-C Implementation of the QuickConnectiPhone Architecture
- Summary
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 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.