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

  • Print
  • + Share This
This chapter is from the book

Section 2: Objective-C Device Activation

This section assumes you are familiar with Objective-C and how it is used to create iPhone applications. If you are not familiar with this, Erica Sadun's book The iPhone Developer's Cookbook is available from Addison Wesley. If you just want to use the QuickConnectiPhone framework to write JavaScript applications for the iPhone, you do not have to read this section.

Using Objective-C to vibrate the iPhone is one of the easiest behaviors to implement. It can be done with the following single line of code if you include the AudioToolbox framework in the resources of your project.


The question then becomes, "How can I get the AudioServicesPlaySystemSound function to be called when the UIWebView is told to change its location?"

The QuickConnectViewController implements the shouldStartLoadWithRequest delegate method. Because the delegate of the embedded UIWebView, called aWebView, is set to be the QuickConnectViewController this method is called every time the embedded UIWebView is told to change its location. The following code and line 90 of the QuickConnectViewController.m file show this delegate being set.

[aWebView setDelegate:self];

The basic behavior of the shouldStartLoadWithRequest function is straightforward. It is designed to enable you to write code that decides if the new page requested should actually be loaded. The QuickConnectiPhone framework takes advantage of the decision-making capability to disallow page loading by any of the requests made by the JavaScript calls shown in Section 1 and execute other Objecive-C code.

The shouldStartLoadWithRequest method has several parameters that are available for use. These include

  • curWebView—The UIWebView containing your JavaScript application.
  • request—A NSURLRequest containing the new URL among other items.
  • navigationType—A UIWebViewNavigationType that can be used to determine if the request is the result of the user selecting a link or if it was generated as a result of some other action.
    -(BOOL)webView:(UIWebView *)curWebView
       shouldStartLoadWithRequest:(NSURLRequest *)request

The URL assembled by the makeCall JavaScript function that causes the device to vibrate, call?cmd=playSound&msg=-1 is contained in the request object and is easily retrieved as a string by passing the URL message to it. This message returns an NSURL-type object, which is then passed the absoluteString message. Thus, an NSString pointer representing the URL is obtained. This string, seen as url in the following code, can then be split into an array using the ? as the splitting delimiter, yielding an array of NSString pointers.

NSString *url = [[request URL] absoluteString];
NSArray *urlArray = [url componentsSeparatedByString:@"?"];

urlArray contains two elements. The first is the call portion of the URL and the second is the command string cmd=playSound&msg=-1. To determine which command to act on and any parameters that might need to be used, in this case the –1, the command string requires further parsing. This is done by splitting the commandString at the & character. This creates another array called urlParamsArray.

NSString *commandString = [urlArray objectAtIndex:1];
NSArray *urlParamsArray = [commandString
//the command is the first parameter in the URL
cmd = [[[urlParamsArray objectAtIndex:0]
componentsSeparatedByString:@"="] objectAtIndex:1];

In this case, requesting that the device to vibrate, the first element of the urlParamsArray array becomes cmd=playSound and the second is msg=-1. Thus, splitting the elements of the urlParamsArray can retrieve the command to be executed and the parameter. The = character is the delimiter to split each element of the urlParamsArray.

Lines 1– 3 in the following example retrieve the parameter sent as the value associated with the msg key in the URL as the NSString parameterArrayString. Because the JavaScript that assembled the URL converts all items that are this value to JSON, this NSString is an object that has been converted into JSON format. This includes numbers, such as the current example, and strings, arrays, or other parameters passed from the JavaScript. Additionally, if spaces or other special characters appear in the data, the UIWebView escapes them as part of the URL. Therefore, lines 6–8 in the following code is needed to unescape any special characters in the JSON string.

1 NSString *parameterArrayString = [[[urlParamsArray
2   objectAtIndex:1] componentsSeparatedByString:@"="]
3   objectAtIndex:1];
4   //remove any encoding added as the UIWebView has
5   //escaped the URL characters.
6   parameterArrayString = [parameterArrayString
7     stringByReplacingPercentEscapesUsingEncoding:
8     NSASCIIStringEncoding];
9   SBJSON *generator = [SBJSON alloc];
10   NSError *error;
11   paramsToPass = [[NSMutableArray alloc]
12   initWithArray:[generator
13      objectWithString:parameterArrayString
14      error:&error]];
15   if([paramsToPass count] == 0){
16       //if there was no array of data sent then it must have
17     //been a string that was sent as the only parameter.
18     [paramsToPass addObject:parameterArrayString];
19   }
20   [generator release];

Lines 9–14 in the previous code contain the code to convert the JSON string parameterArrayString to a native Objective-C NSArray. Line 9 allocates a SBJSON generator object. The generator object is then sent the objectWithString message seen in the following:

- (id)objectWithString:(NSString*)jsonrep error:(NSError**)error;

This multipart message is passed a JSON string, in this case parameterArrayString, and an NSError pointer error. The error pointer is assigned if an error occurs during the conversion process. If no error happens, it is nil.

The return value of this message is in this case the number –1. If a JavaScript array is stringified, it is an NSArray pointer, or if it is a JavaScript string, it is an NSString pointer. If a JavaScript custom object type is passed, the returned object is an NSDictionary pointer.

At this point, having retrieved the command and any parameters needed to act on the command, it is possible to use an if or case statement to do the actual computation. Such a set of conditionals is, however, not optimal because they have to be modified each time a command is added or removed. In Chapter 2, this same problem is solved in the JavaScript portion of the QuickConnectiPhone architecture by implementing a front controller function called handleRequest that contains calls to implementations of application controllers. Because the problem is the same here, an Objective-C version of handleRequest should solve the current problem. Section 3 covers the implementation of the front controllers and application controllers in Objective-C. The following line of code retrieves an instance of the QuickConnect object and passes it the handleRequest withParameters multimessage. No further computation is required within the shouldStartLoadWithRequest delegate method.

[[QuickConnect getInstance] handleRequest:cmd withParameters:paramsToPass];

Because the QuickConnect objects' handleRequest message is used, there must be a way of mapping the command to the required functionality as shown in Chapter 2 using JavaScript. The QCCommandMappings object found in the QCCommandMappings.m and .h files of the QCObjC group contains all the mappings for Business Control Objects (BCO) and View Control Objects (VCO) for this example.

The following code is the mapCommands method of the QCCommandMappings object that is called when the application starts. It is passed an implementation of an application controller that is used to create the mappings of command to functionality. An explanation of the code for the mapCommandToVCO message and the call of mapCommands are found in Section 3.

1 + (void) mapCommands:(QCAppController*)aController{
2   [aController mapCommandToVCO:@"logMessage" withFunction:@"LoggingVCO"];
3   [aController mapCommandToVCO:@"playSound" withFunction:@"PlaySoundVCO"];
4   [aController mapCommandToBCO:@"loc" withFunction:@"LocationBCO"];
5   [aController mapCommandToVCO:@"sendloc" withFunction:@"LocationVCO"];
6   [aController mapCommandToVCO:@"showDate" withFunction:@"DatePickerVCO"];
7   [aController mapCommandToVCO:@"sendPickResults" withFunction:@"PickResultsVCO"];
8   [aController mapCommandToVCO:@"play" withFunction:@"PlayAudioVCO"];
9   [aController mapCommandToVCO:@"rec" withFunction:@"RecordAudioVCO"];
10 }

Line 3 of the previous code is pertinent to the current example of vibrating the device. As seen earlier in this section, the command received from the JavaScript portion of the application is playSound. By sending this command as the first parameter of the mapCommandToVCO message and PlaySoundVCO as the parameter for the second portion, withFunction, a link is made that causes the application controller to send a doCommand message with the –1 parameter to the PlaySoundVCO class. As you can see, all the other commands in the DeviceCatalog example that are sent from JavaScript are mapped here.

The code for the PlaySoundVCO to which the playSound command is mapped is found in the PlaySoundVCO.m and PlaySoundVCO.h files. The doCommand method contains all the object's behavior.

To play a system sound, a predefined sound, of which vibrate is the only one at the time of writing this book, must be used or a system sound must be generated from a sound file. The doCommand of the PlaySoundVCO class shows examples of both of these types of behavior.

1 + (id) doCommand:(NSArray*) parameters{
2     SystemSoundID aSound =
3       [((NSNumber*)[parameters objectAtIndex:1]) intValue];
4     if(aSound == -1){
5         aSound = kSystemSoundID_Vibrate;
6     }
7     else{
8         NSString *soundFile =
9          [[NSBundle mainBundle] pathForResource:@"laser"
10                 ofType:@"wav"];
11         NSURL *url = [NSURL fileURLWithPath:soundFile];
12         //if the audio file is takes to long to play
13         //you will get a -1500 error
14         OSStatus error = AudioServicesCreateSystemSoundID(
15          (CFURLRef) url, &aSound );
16    }
17    AudioServicesPlaySystemSound(aSound);
18    return nil;
19 }

As seen in line 4 in the previous example, if the parameter with the index of 1 has a value of –1, the SystemSoundID aSound variable is set to the defined kSystemSoundID_Vibrate value. If it is not, a system sound is created from the laser.wav file found in the resources group of the application, and the aSound variable is set to an identifier generated for the new system sound.

In either case, the C function AudioServicesPlaySystemSound is called and the sound is played or the device vibrates. If the device is an iPod Touch, requests for vibration are ignored by the device. In an actual application that has multiple sounds, this function can easily be expanded by passing other numbers as indicators of which sound should be played.

Because the SystemSoundID type variable is actually numeric, the system sounds should be generated at application start and the SystemSoundIDs for each of them should be passed to the JavaScript portion of the application for later use. This avoids the computational load of recreating the system sound each time a sound is required, and therefore, increases the quality of the user's experience because there is no delay of the playing of the sound.

Having now seen the process of passing commands from JavaScript to Objective-C and how to vibrate the device or play a short sound, it is now easy to see and understand how to pass a command to Objective-C and have the results returned to the JavaScript portion of the application.

Because these types of communication behave similarly, GPS location detection, which is a popular item in iPhone applications, is shown as an example. It uses this bidirectional, JavaScript-Objective-C communication capability of the QuickConnectiPhone framework.

As with the handling of all the commands sent from the JavaScript framework, there must be a mapping of the loc command so that the data can be retrieved and a response sent back.

[aController mapCommandToBCO:@"loc" withFunction:@"LocationBCO"];
[aController mapCommandToVCO:@"sendloc" withFunction:@"LocationVCO"];

In this case, there are two mappings: The first is to a BCO and the second is to a VCO. As discussed in Chapter 2, BCOs do data retrieval and VCOs are used for data presentation.

Because BCOs for a given command are executed prior to all of the VCOs by the QuickConnectiPhone framework, a doCommand message is first sent to the LocationBCO class, which retrieves and returns the GPS data. The following doCommand method belongs to the LocationBCO class. It makes the calls required to get the device to begin finding its GPS location.

+ (id) doCommand:(NSArray*) parameters{
    QuickConnectViewController *controller = (QuickConnectViewController*)[parameters objectAtIndex:0];
    [[controller locationManager] startUpdatingLocation];
    return nil;

This method starts the GPS location hardware by retrieving the first item in the parameter's array that is passed into the method and informing it to start the hardware. The framework always sets the first parameter to be the QuickConnectViewController so that it can be used if needed by BCOs or VCOs associated with any command. In all of the Objective-C BCOs and VCOs any parameters sent from JavaScript begin with an index of 1.

The QuickConnectViewController object has a built in CLLocationManager attribute called locationManager that is turned on and off as needed by your application. It is important not to leave this manager running any longer than needed because it uses large amounts of battery power. Therefore, the previous code turns the location hardware on by sending it a startUpdatingLocation message each time a location is needed. The location hardware is turned off once the location is found.

CLLocationManager objects behave in an asynchronous manner. This means that when a request is made for location information, a predefined callback function is called after the location has been determined. This predefined function allows you access to the location manager and two locations: a previously determined location and a current location.

The location manager works by gradually refining the device's location. As it does this, it calls didUpdateToLocation several times. The following code example finds out how long it takes to determine the new location. Line 9 determines if this is less than 5.0 seconds and if it is terminates the location search.

1  (void)locationManager:(CLLocationManager *)manager
2      didUpdateToLocation:(CLLocation *)newLocation
3        fromLocation:(CLLocation *)oldLocation
4 {
5     // If it's a relatively recent event, turn off updates to save power
6     NSDate* eventDate = newLocation.timestamp;
7     NSTimeInterval howRecent =
8             [eventDate timeIntervalSinceNow];
9     if (abs(howRecent) < 5.0){
10         [manager stopUpdatingLocation];
11         NSMutableArray *paramsToPass =
12           [[NSMutableArray alloc] initWithCapacity:2];
13         [paramsToPass addObject:self];
14         [paramsToPass addObject:newLocation];
15         [[QuickConnect getInstance]
16             handleRequest:@"sendloc"
17               withParameters:paramsToPass];
18    }
19    // else skip the event and process the next one.
20 }

Having terminated the location search, the code then sends a message to the QuickConnect front controller class stating that it should handle a sendloc request with the QuickConnectViewController, self, and the new location passed as an additional parameter.

The sendloc command is mapped to the LocationVCO handler whose doCommand method is seen in the following example. This method retrieves the UIWebView called webView from the QuickConnectViewController that made the original request for GPS location information. It then places the GPS information into the NSArray called passingArray.

To pass the GPS information back to the webView object, the NSArray within which it is contained must be converted into a JSON string. The same SBJSON class used earlier to create an array from a JSON string is now used to create a NSString from the NSArray. This is done on lines 21 and 22:

1 + (id) doCommand:(NSArray*) parameters{
2     QuickConnectViewController *controller =
3    (QuickConnectViewController*)[parameters
4      objectAtIndex:0];
5     UIWebView *webView = [controller webView];
6     CLLocation *location = (CLLocation*)[parameters
7       objectAtIndex:1];
9     NSMutableArray *passingArray = [[NSMutableArray alloc]
10      initWithCapacity:3];
11     [passingArray addObject: [NSNumber numberWithDouble:
12     location.coordinate.latitude]];
13     [passingArray addObject: [NSNumber numberWithDouble:
14      location.coordinate.longitude]];
15     [passingArray addObject: [NSNumber numberWithFloat:
16      location.altitude]];
18     SBJSON *generator = [SBJSON alloc];
20     NSError *error;
21     NSString *paramsToPass = [generator
22      stringWithObject:passingArray error:&error];
23     [generator release];
24     NSString *jsString = [[NSString alloc]
25     initWithFormat:@"handleJSONRequest('showLoc', '%@')",
26       paramsToPass];
27   [webView
28     stringByEvaluatingJavaScriptFromString:jsString];
29     return nil;
30 }

After converting the GPS location information into a JSON string representing an array of numbers, a call is made to the JavaScript engine inside the webView object. This is done by first creating an NSString that is the JavaScript to be executed. In this example, it is a handleJSONRequest that is passed showLoc as the command and the JSON GPS information as a string. As seen in Section 1, this request causes the GPS data to appear in a div in the HTML page being displayed.

Having seen this example, you can now look at the DatePickerVCO and PickResultsVCO in the DeviceCatalog example and see how this same approach is used to display the standard date and time selectors, called pickers, that are available in Objective-C. Although predefined pickers available using JavaScript within the UIWebView, they are not as nice from the user's point of view as the standard ones available from within Objective-C. By using these standard ones and any custom ones you may choose to define, your hybrid application will have a smoother user experience.

  • + 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.


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.


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.


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.


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


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


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.


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.


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