Using iPhone UIWebView Class with local CSS & JavaScript resources 

This post will cover the basic setup and creation of an application with web content for iPhone that will load local CSS and some useful JavaScript functions. Most of these hints I found partially in different blogs and forums listed in the reference section. The idea is to collect all them together. You can use the following technique to create a more attractive application design.

Creating an application using UIWebView control is not the focus of this post. Here is a helpful beginner’s tutorial for creating an application using UIWebView. We assume that you are already familiar with this topic.
 

UIWebView load

Our work will start with a little change in calling load method of the UIWebView instance. Instead of loadRequest

 [[webView graphWebView] loadRequest:requestObj]; 

we use the loadHTMLString method, providing an NSString object that contains HTML code of our page as a parameter:

 [[webView graphWebView] loadHTMLString:htmlPageStr baseURL:baseURL]; 

To get this page to load resources and styles correctly, you have to set up the right URL:

Set baseURL property of UIWebView to refer your bundle's resources directory

MentorMate
Initial loading screen with progress indicator

On the following reference[2] you can find a short and clear revision of the problem of displaying local images in a UIWebView. To use relative paths or files in UIWebView, you have to load the HTML into the view with the correct baseURL parameter. The following example shows how to do this:

 NSString *path = [[NSBundle mainBundle] bundlePath]; 
NSURL *baseURL = [NSURL fileURLWithPath:path]; 

And then call load method of UIWebView provide above NSURL parameter:

 [[webView graphWebView] loadHTMLString:pageStr baseURL:baseURL]; 

A short explanation: An NSBundle object represents a location in the file system that groups code and resources that can be used in a program. mainBundle method returns the NSBundleobject that corresponds to the directory where the current application executable is located. bundlePath instance method of NSBundle returns the full pathname of the receiver’s bundle directory. NSURL class is used to create an object which will hold the URL information. It provides a way to manipulate URLs and the resources they reference. loadHTMLString method of UIWebView has parameter baseURL that accept an NSURL object instead of a pathname as the file reference. Giving the above baseURL to UIWebView, you can refer to your bundle's resources directory like this:

  <img src="myimage.png">   

Or from within CSS like this:

 background-image: url(loading.gif)   

It’s important to note that resources (images, CSS and JavaScript Files) inside your application bundle are at the root of the bundle, even if you place them in an separate group (folder) in your project. Giving the correct URL to UIWebView will allow you to refer to local resources in your page, but it does not work in all cases. If you want to use JavaScipt, some additional settings have to be done.

Link a CSS and JavaScript files

MentorMate
Second loading screen with progress indicator

Now you can use generic HTML technique to add CSS and JavaScript to the web page and displaying in a UIWebView.

<link href="default.css" rel="stylesheet" type="text/css" /> 
<script type="text/javascript" src="showhide.js"></script> 

Do not forget to add your CSS and Javascript files to the xCode project (if you are using external files).

Some additional actions have to be taken before starting your application and using JavaScript functions.[3]

XCode setup (*.js) javascript as some type of source code needs to be compiled in the application. We would like to include it as a resource so I've solved it by doing two things:

  1. Select .js file and in the "Detail" view unselect the bullseye column indicating it is compiled code
  2. In the "Groups & files" view expand the "Targets" tree and expand the application then go to "Copy Bundle Resources" and drag the *.js files into it.

The Apple dev forums has a posted solution. [4] You need to do two things - select the .js file in your project, and turn off the checkbox that indicates that it is compiled (the "bullseye" column). If you don't do this, you'll get a warning in your build log about being unable to compile the file (which should be your first warning - always try to figure out and and correct any and all warnings that appear in your build).

Set transparent background color for UIWebView

MentorMate
Final screen with graph representation.

In our example we need to figure out a transparent background for UIWebView. On the parent View Container we have additional controls (buttons, labels) and already defined background. The following code will set this:

 [[webView graphWebView]
setBackgroundColor:[UIColor clearColor]];</code> 
[[webView graphWebView] setOpaque:NO];  

Example

MentorMateDemoJS is a simple application example which uses the settings described above. It is a view-based application that shows a graphical representation of some data. Application behavior consists of a predefined call with formatted data to Vvidget Service[5] for graph generation. The service returns an image that is loaded in UIWebView Design Resource. The update button is added to resend the graph request and update view.

The Problem: Graph image requires some time for loading.

Our Decision: Notify user of graph loading process by showing a progress bar during load time.

To achieve this, we use UIWebView with local resource of two JavaScript functions. One to show/hide notification messages and the other to visualize a progress bar during loading time. In the provided sources you can find all these steps implemented.

Sources of the example iPhone application

References

  1. iPhone SDK Articles, UIWebView Tutorial, August 19, 2008
  2. iPhone Development Blog, UIWebView – Loading External Images and CSS, February, 2009
  3. StackOverflow, iPhone UIWebView local resources using Javascript and handling onorientationChange
  4. Developer Forum, UIWebView and JavaScript, 2009
  5. Vvidget, Vvidget Server™ Reference Manual , 2010
Teaser: 

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

wonderful right and wonderful

wonderful right and wonderful explanation. Absolutely what I needed. Appreciate the effort putting up the article - leaving no ambiguity

I hope, the following code

I hope, the following code will help you to understand. NSDate *epoch; NSMutableString *data = [[@"&data_1=" mutableCopy] autorelease]; .... NSTimeInterval timeInterval = [epoch timeIntervalSince1970]; [data appendString:[NSString stringWithFormat:@" %.01f %d", timeInterval, value ]]; ....

thanx for the Javascript

thanx for the Javascript point that was very helpfull for me

I am entirely new to this

I am entirely new to this Javascript, CSS and HTML. This code is really useful to take a bit step ahead with confident. I had a doubt that how date is assigned in X axis. My understanding from the below is 59 --> Y axis value but I dont understand this 1265886924.5. Could u pls explain me? static NSString *TEST_DATA = @"&data_1= 1265886924.5 59 1265973324.5 17 ....." Thanks in advance. Regards, C.Karuna.

Thanks for this nugget. The

Thanks for this nugget. The bit about adding the .js to the Copy Bundle Resources was my missing link.

When I downloaded the source

When I downloaded the source to play in XCode there isn't any .xcode project file. Do you have that handy as well? Thanks!

Thank you, thank you! You're

Thank you, thank you! You're awesome for writing this up and saving me a lot of time.

Thanks for doing this. I was

Thanks for doing this. I was pulling my hair out trying all sorts of combinations to get the baseURL correct. Turns out the js no compile / move to bundle targets did the trick. Thanks again.