- Section 1: JavaScript Device Activation
- Section 2: Objective-C Device Activation
- Section 3: Objective-C Implementation of the QuickConnectiPhone Architecture
- Summary
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.
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
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 navigationType:(UIWebViewNavigationType)navigationType
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 componentsSeparatedByString:@"&"]; //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]; 8 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]]; 17 18 SBJSON *generator = [SBJSON alloc]; 19 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.