Hybrid iPhone Applications

Increase your speed to market by building a hybrid application for iPhone

Hybrid Applications

Last week we learned how to build “Native Web” applications for Android.

That was fun, but what exactly is a hybrid application?

A true native application is one that is written with the SDK of the target platform — Java for Android, Objective-C/Cocoa Touch for iPhone.

A relatively new term has become main-stream in the mobile space — the hybrid application.

No, this doesn’t mean we run it on soybeans or ethanol — this term has come to describe the “native web” approach where the application is written and compiled in the “SDK”, however the primary user interface is implemented in HTML, CSS and Javascript running inside of the platform’s “web” control. This is the web developer’s on-ramp to mobile application development and when used judiciously, can lower your time to market for the right kind of applications.

Last week was Android’s turn — this week we build an iPhone application to see how the hybrid architecture works here.

In this article we build a simple application for iPhone which leverages the UIWebView control to display our own, albeit simplistic, HTML interface. While the high-level architecture is very similar to what we saw for Android, the implementation is a bit different. I personally prefer the Android approach, however the iPhone approach is certainly workable.

As a further piece of information before we get started: there are more sophisticated tools available to build these kinds of applications. Appcelerator Titanium and the PhoneGap project are top of mind. If you want to get started right away building applications for the Apple App Store, you might want to check out one of those tools.

If you are curious as to just how this works for iPhone and you are perhaps one of those people whose favorite HTML editor is “vi” or “notepad”, stick around and check out this week’s application.

To give credit where it is due, I have modeled this approach after the techniques used by the PhoneGap project. If there are more clever ways of doing this that you have run across, please let me know!

iPhone Application

One of the goals of our application is to be “native” — meaning that it can be installed on the device, run off-line (if desired) and ultimately be distributed to other users. The most likely scenario for that distribution is via the App Store. The image below shows the launcher screen of the iPhone simulator with our application’s icon circled.


When we load the application by selecting the icon, our application presents a super simple HTML interface — remember we are more interested in the inner-workings of this application than its visual appeal. Excuses, excuses…

The page contains a single link to linuxdlsazine (of course…), three buttons, an HTML <span> and a graphic. Here is the HTML used in the application.

<a href='http://linuxdls.com'>Visit linuxdlsazine</a><br />
<br />
<br />
<button style="color:red" onclick="document.location = 'linuxmag://color/background?red'";>Cornell Big Red</button><br />
<button style="color:blue" onclick="document.location = 'linuxmag://color/background?blue'";>Blue Devils</button><br />
<button style="color:green" onclick="document.location = 'linuxmag://color/background?green'";>Green Wave</button><br />
Msg:<span style="background-color:yellow"id='msg'>something of interest can go here....</span>
<br /><br />
<img src="lmlogo.jpg" />

The image below shows the application as it appears when the app is launched:


Selecting the link will bring up the target link:


Note that we have not included any browser navigation tools like back, forward, etc. in this application — this link is here just to show that we can link to an external site if desired, though that is not the focus of this application. We will learn more about how links are handled in just a moment when we start looking at the Objective-C code.

Returning our focus to the buttons on our HTML page — each is labeled with a colored piece of text, listing a couple of NCAA basketball power houses along with an another Ivy Leage team. Selecting any of the buttons causes the time to be written to the HTML page with a different back-color as shown here:


Sorting out exactly how this happens is the purpose of this application. Now, to be fair, this functionality certainly doesn’t require a native application — it is merely demonstrative of higher-purpose functionality that a hybrid application can perform. Let’s look at how this works in Objective-C.


Our project is constructed in X-Code. For those who missed the memo, you can only develop native, or in this case hybrid, iPhone applications on an Intel-based Mac. The screen show below shows our project loaded in X-Code:


For all the busy-ness of the X-Code project, we are mostly concerned with the hiaAppDelegate.* files. Let’s look first at the header file:

//  hiaAppDelegate.h
//  hia
//  Created by Frank Ableson on 12/7/09.
//  Copyright MSI Services, Inc. 2009. Use as you like :)

#import <UIKit/UIKit.h>

@interface hiaAppDelegate : NSObject <UIApplicationDelegate,UIWebViewDelegate> {
    UIWindow *window;
	UIWebView *browser;

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UIWebView *browser;

Most of the code around property and nonatomic etc. are beyond our focus right now. What we want to look at is the fact that this particular class implements the “UIWebViewDelegate” protocol and that we define an instance of the UIWebView class. This is how we interface with HTML, CSS and Javascript. Using this class in the way we do is what makes this application a “hybrid” app.

The UIWindow was created as part of the automagically iPhone project when you select “New Project”. One thing to make note of here is the IBOutlet keyword — that indicates that this particular variable is connected to a “widget” defined in the InterfaceBuilder application, X-Codes drag-n-drop GUI builder.

That is the usual and ordinary way user interface elements are created in iPhone development. However, please note that we are NOT using that approach for working with our UIWebView. Remember your early commitment to vi and notepad?

By keeping all of our interactions with the UIWebView class directly in code, it will hopefully take some of the mystery out of working with it. Let’s see how our UIWebView object is instantiated.

The code for the method applicaitionDidFinishLaunching is shown below, along with comments to help you understand what is happening.

  • Make the main window visible.
  • Setup the UIWebView control, set its dimensions.
  • Assign the delegate, which will allow us to override default behavior — this is the key to the hybrid application and is discussed further below.
  • Setup a local file to be loaded into the UIWebView. Seems like a lot of work to say, “load index.html”.
  • Add the browser to the main screen.
  • If you prefer a more “immersive” experience, you can remove the application’s status bar by uncommenting the last line.
- (void)applicationDidFinishLaunching:(UIApplication *)application {    

   // show main window
	[window makeKeyAndVisible];

   // instantiate the UIWebView object -- assign it to the variable "browser"
   // set the control to take most of the screen via the CGRectMake macro
	browser = [[UIWebView alloc] initWithFrame:CGRectMake(0,20,320,460)];

	// assign the object's delegate
   browser.delegate = self;		

   // load up the index.html file included in the project
	NSURL *startUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle]  pathForResource:@"index" ofType:@"html"]];
	NSURLRequest * startRequest = [NSURLRequest requestWithURL:startUrl];
	[browser loadRequest:startRequest];

	// add the control to the main window
	[window addSubview:browser];

//	[[UIApplication sharedApplication] setStatusBarHidden:YES];

At this point our application is running, and the index.html file is rendered into the UIWebView, drawn to the main window. What happens when the user selects something? The method shouldStartLoadWithRequest is invoked. Here is the code and some basic explanation.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	NSURL *url = [request URL];

	NSLog([NSString stringWithFormat:@"URL is : [%@]",[url absoluteString]]);

	switch(navigationType) {
		case UIWebViewNavigationTypeLinkClicked:
			NSLog(@"Nav type: Link selected.");
		case UIWebViewNavigationTypeFormSubmitted:
			NSLog(@"Nav type: Form Submitted.");
		case UIWebViewNavigationTypeBackForward:
			NSLog(@"Nav type: Back/Forward");
		case UIWebViewNavigationTypeReload:
			NSLog(@"Nav type: Reload");
		case UIWebViewNavigationTypeFormResubmitted:
			NSLog(@"Nav type: Form Re-Submitted?");
		case UIWebViewNavigationTypeOther:
			NSLog(@"Nav type: Other");
			NSLog(@"Nav type: Something else...");
	if ([[url scheme] isEqualToString:@"linuxmag"]) {
		NSLog([NSString stringWithFormat:@"host is [%@] query is [%@] path is [%@] paramterString is [%@]",(NSString *) [url host],(NSString *) [url query],(NSString *) [url path],(NSString *) [url parameterString]]);

		if ([[url host] isEqualToString:@"color"]) {
			if ([[url path] isEqualToString:@"/background"]) {
				[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('msg').style.backgroundColor = \"%@\";",[url query]]];
	    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('msg').innerHTML = \"%@\";",[[NSDate date] description]]];
	   return NO;
	return YES;
  • This code is invoked prior to the browser control loading new content.
  • For fun, we examine the navigationType. To be candid, I was just curious as to what it would do — you may find some value in it. In particular, watch this as you load an external page with multiple image and script links downloaded. The NSLog() function drops message to the debug window in X-Code.
  • We look at the “scheme”. This is typically http or ftp. To customize content for our hybrid application, we define our own “scheme”. In this case, we use the keyword linuxmag. If the code encounters a link with linuxmag, we handle it in a special fashion.
  • Assuming we’re working with one of our linuxmag URLs, we then break down the URL into host, query and path. Based on these values we can perform various application-specific functionality.
  • To interact with the html content, we use the stringByEvaluatingJavaScriptFromString message. You just have to love those verbose names!
  • We update the back-color by manipulating the style and then populate the innerHTML to contain the date.

If we want tell the browser to not load a particular page, we can filter them out by returning NO rather than YES.

Unlike the Android approach of mapping Javascript functions directly to Java functions, this approach requires us to crack each URL and parse out the various elements — including scheme, path, and query name/value pairs if you are so inclined.

It may be a consequence of running on the emulator, but I felt that the application was a bit more sluggish than the Android application we built last week. Fast or slow, this approach is perfectly valid, and arguably more consistent with an Ajax-ian feel to it where so much takes place with constructed URLs as opposed to more function calls within the Javascript environment. I personally prefer the Android approach, but this works too.

Regardless of how you feel about having to parse-out commands from URLs, the advantage of the hybrid approach to iPhone application development is that you can focus your HTML skills on the UI and then do basic Objective-C coding for the plug-and-chug portions of your application, without getting caught up in the myriad of Cocoa Touch classes. Let CSS do the work for you. This won’t work for every application but for many line of business applications, this approach can speed time to market.

As usual, the code for this application is available on the Code Hosting site.

Well, that wraps up our introduction to the hybrid iphone application. And, just for fun, the first reader to name the basketball team I played for (hint, it’s in the html), I’ll send a copy of the Unlocking Android ebook.

Comments on "Hybrid iPhone Applications"

Do you know the number for ? glipizide tablets side effects Selling in the euro, which was last off 0.26 percent against the dollar at $1.2746, quickened after the shared currency sank below the $1.2750 level, according to Boris Schlossberg, managing director at BK Asset Management in New York.

I’ll send you a text cheap losartan Should pricing beconfirmed at that level, it would value the deal at 87.55million pounds, according to Reuters calculations.

I’m in my first year at university where can i buy ibuprofen gel â??Pressing? Yeah, at times when Iâ??m underneath trees and Iâ??m in bunkers and trying to get up and down, yeah,â? he replied. â??As far as the overall game plan and the way Iâ??m playing, Iâ??ve been in enough of these things where Iâ??ve been right there on the back nine on Sunday with a chance. As far as thatâ??s concerned, no.
vytorin generic name “investigators “found that Morgan Stanley’s staff lacked proper training…and that the company failed to adequately supervise its personnel…to the detriment of investors.”

What part of do you come from? buying accutane online forum The world now is not nearly as linear as it was in June of 1941; there is no one clear enemy. There are however, clear problem spots which require the ability to work together from competing international players – first and foremost in Syria.
buy betamethasone cream online Diamond Electric, which will cooperate with the JusticeDepartment, agreed to plead guilty to a single felony charges offixing the prices of ignition coils sold to Ford, Toyota MotorCorp and Fuji Heavy Industries Ltd, the Justice Department said.

Can I call you back? cheap elavil It said: â??Royal Mail is still talking with the CWU to reach a new agreement and calls on the CWU to focus on these talks rather than preparing for industrial action. We wish to reach agreement as soon as possible to provide continued stability for our employees, our business and our customers.â?
synthroid buy online The sweeping proposal aims to establish a new framework forthe U.S. housing finance system and reduce the government’s rolein the market as much as possible, Republicans on the HouseFinancial Services Committee told reporters.

I didn’t go to university wellbutrin or paxil for depression “When I saw him run to first today I thought it was the best I had seen him run in a while,” Girardi said. “He’s a guy that uses his lower half a lot when he’s hitting, and when you don’t have it, it’s a little more difficult.”
silagra 100 mg opinie
Jack was diagnosed with cancer in April 2011. Since then, heâ??s had two surgeries to try to remove the tumors in his brain. For nearly a year, he suffered from secondary epilepsy and had up to eleven partial seizures every day.

A book of First Class stamps dapoxetine bg It does seem that sometimes the Department of Health is damned if it does, damned if it doesn’t. Last week it announced an emergency rescue package for Britain’s 50 worst hospital A&E wards. A total of £500 million will be divvied out over two years, money that will come from underspend in the department.
nexium 40 mg tablets price Davis, who was present at the press conference and said he would work as an adviser, joins Tacopina, arbitration expert David Cornwell, and a team of attorneys from Reed Smith on a roster that also includes other lawyers, PR reps and private investigators.

Please call back later buy terbinafine cream remains a major challenge for any terror group, inspiring “lone wolf” sympathizers to conduct attacks is much easier for terror groups, and not just Al Qaeda and Islamic State

Photography order cardura
If Naimi goes I would think that he wouldprefer to go after there is some order put back into OPEC,” saidOlivier Jakob from consultancy Petromatrix.

I’d like , please free prozac coupons Despite six suspects being identified the day after the killing, the family complained that the police were not doing enough to find the killers – at the same time they made the complaints it is now alleged that resources were being used to watch them.
zyprexa kills ** Russian President Vladimir Putin failed to clinch aconcrete energy deal on a rare trip to Azerbaijan on Tuesday,dashing Moscow’s hopes to challenge the dominance of Westernenergy majors in the former Soviet republic.

I’m on business differin gel amazon uk Observers do not discount the possibility that the companyand its creditors will sign a standstill agreement to give themmore time and perhaps avoid a bankruptcy proceeding that couldprove lengthy and frustrating.
can you buy tamoxifen in australia Santorum’s visit has all the hallmarks of a presidential campaign swing. His political team even released a media advisory detailing Santorum’s stops over the next few days that bears a striking resemblance to his old campaign schedules.

Looking for work buy diamox in peru That entails a complete transformation of the world’s energy system – which isn’t easy to do.

I’m sorry, she’s buy flomax uk Right-handed starter Jake Peavy delivered, giving the bullpen a break with a solid seven-inning outing as the San Francisco Giants jumped to an early lead and cruised to an 8-3 victory over the Chicago Cubs.

What’s your number? where can i buy permethrin 5 cream The American Institute for Cancer Research says half of all cancers are preventable

I’m originally from Dublin but now live in Edinburgh average cost topamax Today, it looks like a crowded Republican field but a small – as in one or two – field on the Democratic side. By the time primary season rolls around, if Biden gets in and does well, the crowd may be on the Democratic side, destroying its candidates with brutally contentious debates, forcing them into untenable positions, as Republicans did to Mitt Romney last time around. And Republicans, who are hashing out their disputes now, a full two years before election day, may well be ready by then to coalesce around one or two well-organized candidates. 
seroquel 5 mg Content engaging our readers now, with additional prominence accorded if the story is rapidly gaining attention. Our WSJ algorithm comprises 30% page views, 20% Facebook, 20% Twitter, 20% email shares and 10% comments.

Where do you study? cheapest way to get accutane Merck told Reuters in a statement that its own probe into the Tyson matter has shown Zilmax is not the cause of the animal behaviors seen at Tyson’s facilities but declined to elaborate further. Merck spokeswoman Pamela Eisele said decades of product research have shown Zilmax is safe for animals, adding that Merck is working with Tyson to determine why Tyson has observed non-ambulatory or lame cattle at some of its beef plants.
medicamento vasotec 10 mg WalesOnline is part of Media Wales, publisher of the Western Mail, South Wales Echo, Wales on Sunday and the seven Celtic weekly titles, offering you unique access to our audience across Wales online and in print.

Nice to meet you tadacip wirkungseintritt Siemens shares jumped almost 5 percent, though the move waaggerated by Deutsche Boerse recalculating theirFriday close to remove the value of the lost Osram stock.Ignoring that adjustment, the stock was up by around 1.8percent.
where can i get doxycycline uk As if on cue, Syrian President Bashar al-Assad backed Putin up by telling a Russian television channel: “Syria is placing its chemical weapons under international control because of Russia. The U.S. threats did not influence the decision.”

I’m from England tadacip wirkungsdauer At an inquest earlier this month, deputy assistant coroner for Gloucestershire Tom Osborne said he was concerned about the way the college handled cases of children in crisis, and that he was considering recommending a specific suicide prevention policy.
order nexium from canada
The problem with this idea is that in principle neighbourhood watch schemes benefit the participants, everyone gains something by taking part. with this scheme some people will do work for others with no imediate benefit to themselves. The fear will be that after the initial enthusiasm most participants will drop away, leaving those with the greatest empathy doing an unreasonable amount of work.

I don’t like pubs order nexium from canada
The report, published on Saturday, acknowledges that UKBA has had a “troubled history” but questions how ministers intend to prevent its problems “outliving its demise”. “The newly appointed directors general must have the ability and resources necessary to implement this change. The Home Office should outline exactly how they propose to bring about this change in culture.”
orderpharma accutane At 1600 Pennsylvania Ave., Cecil watches as President Eisenhower (Robin Williams) wrestles with the violence in Little Rock. Cecil later meets John F. Kennedy (James Marsden) and Jacqueline Kennedy (Minka Kelly) and sees the face of change; notices LBJ (Liev Schreiber) try to craft an uneven New Society; catches Nixon (John Cusack) asking the black staff about their lives, and hears Reagan (Alan Rickman) veto sanctions against South Africa.

Have you got any experience? buy generic lamictal online
The new law allows voters to cast a provisional ballot if they come to a polling station without proper ID. The hours to cast an early ballot remain the same, and there will be 10 days for voters to cast their ballot early.
finasteride uk side effects Do you have any recommendations about holidays specialising in food and drink? It could involve a food festival, a wine tasting, or a region known for its markets or restaurants. Perhaps, it is something more hands on, such as grape picking, truffle hunting or even sea fishing. The sender of the best entry will win a festive three-night break in Cologne (for dates, see below) with Ffestiniog Travel, including b & b and Eurostar travel.

I’m not working at the moment where can i buy omeprazole over the counter “Ineos is delighted that this offer is now being made,albeit through the media. This offer will mean that Ineos canmaintain North Sea oil flows and fuel supplies to the people ofScotland,” Ineos said in a statement.
cheapest pharmacy to buy propecia For example, despite being a match in the sixth tier of the English game, played out in front of just 408 spectators, hundreds of thousands of pounds was placed on Billericay's away match at Welling in November, the vast majority of it on Asian betting exchanges.

Who’s calling? super p force bestellen “What I’ve said to him is we are happy to negotiate on anything,” he continued. “But what we can’t do is keep engaging in this sort of brinksmanship where a small faction of the Republican Party ends up forcing them into brinksmanship to see if they can somehow get more from negotiations by threatening to shut down the government or threatening America not paying its bills.”
ibuprofeno (advil motrin ib) o paracetamol (tylenol) â??Weâ??re here today to announce that we do now have a cause of death in the tragic death of Cory Monteith. That cause of death was a mixed toxicity, and it involved heroin, primarily, and also alcohol,â? said Barb McLintock of the British Columbia Coronerâ??s Service.

How long have you lived here? buy isoptin online The pressure is on him after a two-month absence from the PGA Tour that followed an abysmal stretch in which his best finish in six official events was 69th at the British Open, dropping his ranking to 111th.

How long have you lived here? cheap generic micardis But lately, she’s been staying in her room and refusing to take her medication

I’ve only just arrived purchase omeprazole Kaepernick and the 49ers departed for their flight home with playoff hopes still ahead of them

I’m a housewife purchase micardis In the wake of the Amnesty International report, Rio's Civil Police announced that police killings during “acts of resistance”, where a suspect is being pursued, would now be investigated by the homicide division instead of by officers in local headquarters.

Leave a Reply