Subscribe ( RSS )

iPhone Programming Tutorials


 

iPhone Coding - Learning About UIWebViews by Creating a Web Browser

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Wow! It has been a long time since my last tutorial… As I wrote in my last post, I had to take a break due to my wife having our baby.  But, now I’m back and have a great tutorial for you guys.  

Today I will be showing you how to work with a  UIWebview to create a basic web browser.  Here is a screenshot of the app we are going to create.

screenshot_02

Create a View-Based Application

Ok, so let’s get started.  Start by opening up Xcode and click File -> New Project.  Next select View-Based Application and click Choose… Name this project something like iCodeBrowser and click Save.  

screenshot_03

screenshot_04

Now we are ready to begin coding…

Create IBOutlets and IBActions

Before we create the interface for our web browser, we need to establish the IBOutles and Actions to interface with the UI elements in code.  Start by opening up iCodeBrowserViewController.h and add the following code:

screenshot_06

Let’s take a look at this code line by line.  The first thing we added was the <UIWebViewDelegate> to the end of our interface declaration.  This is telling the app that this class will be the delegate for our UIWebview.  

What does it mean to be the delegate you ask? Great question… A delegate is like a handler.  It is responsible for implementing certain methods in order to handle events sent by the object they are the delegate for.  So in our example, we are simply saying that we will implement some of the functionality of the UIWebView.  This is needed so we can capture certain actions of the UIWebView such as a click on a link or so we can tell when a page has started/finished loading.  If it’s still unclear, ask me clarifying questions in the comments section.

Next, we see our 3 lines of declaring IBOutlets.  These are the UI elements that we will be interacting with.  In case you didn’t know, the UIActivityIndicator is the little spinner/loading animation that you see on various apps when content is loading.  We will be using this to show that a page is currently loading.

Following this code, there are 3 IBActions.  IBActions are functions that get called in response to a user interaction with the application (such as tapping a button).  For our basic browser, we are only offering 3 types of functionality.  gotoAddress which will take a user to the address they type in the address bar and goBack/Forward should be pretty self explanatory.  

Creating the User Interface 

Now, let’s create the interface using Interface Builder.  I am going to be showing you how to do this in the video below.

 

Implementing the IBActions

Now that we have our interface, let’s make the app function.  We need to implement our methods.  Open up iCodeBrowserViewController.m and add the following code.

screenshot_01

We need to synthesize our properties to allow us to interact with them.  Synthesizing automatically creates “getter” and “setter” methods for our properties.  Next, let’s implement the viewDidLoad method.  This is where we will be loading our “homepage”.  Add the following code to the viewDidLoad method.

screenshot_08

The viewDidLoad method gets called automatically by our application whenever this view first loads.  We can know for sure that it will get called, so we can put our initialization code here.

The first thing we see is the urlAddress string.  This will be our “homepage”.   You can change this to any address you wish to start with.  Next, we build a URL object with our string.  We need to do this so we can make a web request.  Following this, we build our web request and load it into the webView.  This will display the homepage inside of our webview.  Finally, we set the text of the address bar to the homepage address.  This part is more for aesthetics to let the user know what page they are on.

Next, we implement the method that we connected to the UITextField’s DidEndOnExit method gotoAddress.  Add the following code:

screenshot_09

This is similar to the code we wrote in the viewDidLoad method, except for the fact that we are getting our URL string from the address bar.  This method gets called when the user presses the “Go” button on the keyboard.  The last thing to note here is we call the [addressBar resignFirstResponder] method.  This simply tells the app to hide the keyboard when this method gets called.

The implementation of our Back and Forward methods are pretty easy.  Go ahead and add the following code.

screenshot_10

UIWebViews are pretty cool because of the functionality they offer us built right in to them.  We simply call [webView goBAck] to go back and [webView goForward] to go forward.  This greatly simplifies the interactions with the webview.  If we were to code that functionality from scratch, we would have to create a stack of URLs and continually push and pop them off the stack to keep track of where we need to go.  Thanks Apple for not making us implement this.

Finally, we need to implement the delegate methods for UIWebview.  These methods allow us to write our own code to respond to actions by the UIWebview.  The first methods we will implement are the webViewDidStartLoad and the webViewDidFinishLoad methods.  We will use these to show and hide the activity indicator. Add the following code:

screenshot_11

So when the request is first made for a ULR (before the page starts loading) the webViewDidStartLoad method gets called automatically.  We use this opportunity to start our activity indicator to let the user know the page is loading.  If you don’t have something like this, it simply feels like the app is frozen when in fact, it’s just loading the page.  Finally, the webViewDidFinishLoad method gets called when the page is fully loaded.  After this, we can stop the indicator (and it automatically hides itself).

The very last thing we need to do is define what happens when a user clicks on a link. Add the following method:

screenshot_13

This method gets called automatically whenever the user clicks a link.  This method can be very useful if you want to make a native iPhone application that integrates with a web app.  You can use this method to trap the user’s clicks and have your application respond to web links that get clicked.  In our case, we need it to do 2 things.  The first is to set the text of the address bar to the URL of the link that was clicked on and to load that address into the webview.

One thing to make note of: We do a check to see if the URL scheme is “http”. This is to ensure that the user typed http before their URL.  You can add an else statement here that auto prepends the http if the user did not add it.  This would allow you to type in a url such as “icodeblog.com” rather than having to type “http://www.icodeblog.com”.  I chose to omit it for this tutorial.

Remember, all of this added functionality of a UIWebView can only be gotten if you tell your class that it implements the UIWebViewDelegate protocol as we did in our .h file.

The app should be complete! Click on Build and Go to see this baby in action.  Remember, you must put “http://” in front of your URL’s.  

I hope you have enjoyed this tutorial.  If you have any questions or comments, feel free to leave them in the comments section of this post.  You can download the source here . Happy iCoding!

 

 

 

48 Responses

Dan Says:

December 19th, 2008 at 4:20 pm

Congratulations on the new Baby!

Can’t wait to dive into this tutorial, looks like quality work yet again!

iPhone Coding - Learning About UIWebViews by Creating a Web … : businessuu Says:

December 19th, 2008 at 5:05 pm

[...] Original unknown [...]

Sam Green Says:

December 19th, 2008 at 9:23 pm

Congrats!

I was so glad to see some activity from you in my feed reader. Well written and concise. Thanks again for all the hard work. You’ve definitely been an asset to me, and probably a great majority of the iPhone development community. Keep it up!

Joe Says:

December 19th, 2008 at 11:14 pm

Congrats on the baby and thanks so much for all of you wonderful tutorials… I had begun to wonder if something happened to you, but I am glad to see you are back! Hope everything is well. Can’t wait to see more tutorials.

JItesh Says:

December 20th, 2008 at 3:06 am

Thanks for the tutorial …

The tutorial worked perfectly, but I got stuck in one problem,

I try to open gmail using this program and the gmail page was open successfully…..

now when I clicked inside the text box(i.e. Username field) of gmail the UIWebView automatically shifted up side

and the keyboard which should be appeared at the bottom also get shifted upper side and I am able to see only the last three buttons.

by scrolling I get the view back to normal position but … what about keyboard..??

I can’t understand why it is happening like this.

Mike Says:

December 20th, 2008 at 4:05 am

I’ve been enjoying your tutorial. I’m running into a problem. I’ve done the TODO list project and tried to expand on it and try to put a tab bar. Tab bar 1 grabs Todo1 table from sqlite and Tab bar 2 grabs todo2 table. The problem is, everytime I add a new entry into Tab bar 1 and then close the application by clicking home… when i relunch the app… it also creates an blank entry on Tab Bar 2. I need help. Is there a way I can send you the zip file of my project? If not, is it possible for you to create the TODO List project but with tab bars so I can learn. Please =). Thanks in advance.

Kieran Says:

December 20th, 2008 at 8:18 am

Is there anyway to force the uiwebview to only show part of a page. For example I have a table on my webpage and want to show it in a uiwebview but I don’t want the user to be able to navigate the rest of the page, only to see that part.

Fredrik Says:

December 20th, 2008 at 9:45 am

Hi,

The line “@implementation iBrowserViewControll” should be “@implementation iCodeBrowserViewControll”.

At least I needed to change this to get things working ;-)

bobcubsfan Says:

December 21st, 2008 at 1:13 am

Had to modify this method:

-(void)webViewDidStartLoad: (UIWebView *) webView
{
activityIndicator.hidden = NO;
[activityIndicator startAnimating];
}

adding activityIndicator.hidden = NO;

to get it to work.

Otherwise, thanks for the tutorial “dad.”

Brandon Says:

December 21st, 2008 at 2:27 am

@Fredrik

Lol copy and paste error…

@Bob, what was the error that required u to add that code?

@kieren
Make an iphone formatted page on ur site

@Mike

read the tut on tab bars

Bob Schoenburg Says:

December 21st, 2008 at 2:03 pm

No error. Activity indicator did not display. Thanks for the tip about using a fixed spacer in the tab bar. I also used a variant of the indicator to hide the indicator in my app.

-(void)webViewDidFinishLoad: (UIWebView *) webView
{
// Load finished, hide the activity indicator in the status bar
[UIApplication sharedApplication].isNetworkActivityIndicatorVisible = NO;
}

iBob Says:

December 22nd, 2008 at 3:21 pm

Thanks for the nice tuto…
But i need to say that i preferred and loved previous video tutorials with the full guide on it… :)
Thanks a lot.

Tommy Says:

December 24th, 2008 at 4:15 am

i had finished your tut well

it ran on iPhone Simulator but when i winscp it to iphone then it crash , it back to homescreen

what’s it wrong ?

Brandon Says:

December 24th, 2008 at 9:49 am

@Tommy

Why not just use XCode to transfer it to the iPhone. I am not sure about using winscp for this task.

@iBob

I’ll do both. There are about an even number of people that prefer one style over the other. This tut just had a lot of code writing, so I didn’t want to make a 10 min vid of me writing code…

Dunkel Says:

December 29th, 2008 at 7:38 pm

@Tommy

You need to sign the app just after you transfer it via winscp, and why you use winscp? aren’t u working on a mac? you can use cyberduck or something like that

Ricardo Drouyn Says:

January 1st, 2009 at 8:33 pm

I noticed that the last step in setting up your view, you connect the webView and the view as outlets to your icodebrowser view controller. Even though it works, this causes a warning in interface builder saying that this setup isn’t supported. Specifically it says the controller has its ‘NIB Name’ property set and its ‘view’ outlet connected. Any idea why im getting this warning?

Another question I have is for the reasoning behind modifying the mainWindow xib and not the icodebrowser view controller xib. I havent noticed us doing this in previous tutorials.

That is all, thanks for the great work!

Michael Says:

January 2nd, 2009 at 3:44 am

Hey! Thanks for the turtorial. I got up to the video, however, i run into a problem there. After you drap the objects onto the window, I cannot link the Events (i.e Did End on Exit) so the iCodeBrowser in MainWindow.xib. That window turns grey and I cannot drag anything into it. Any reason why?

Thanks!
~Michael

Mike Says:

January 3rd, 2009 at 3:19 pm

Hey buddy… sorry to bother you and I know this question is for an old tutorial… but here’s the question I have for the SQL tutorial that you have.

When I add an entry, the segmented controller is set to the value of low when the view is loaded. Lets say, I change the value to Med and save it. When I try to add another entry… the segmented controller is set to the last value… in this case… Med. My question is… how do I reset the segmented controller to Low everytime I add a new value or when the View is loaded? I’ve checked Apple’s docs and can’t find the answer.

zword Says:

January 9th, 2009 at 10:02 am

I just wanted to know, if you don’t have to set
“webView.delegate = self;” ?

Otherwise the UIWebViewDelegate methods won’t be called.
I was following your tutorial and it didn’t work until I set
“webView.delegate = self;” in the viewDidLoad method.

Moon Says:

January 10th, 2009 at 2:25 pm

Hi
Thanks for all your tutorials,at one time I did loose hope of developing something on iPhone but after reading thru these tutorials I am in race again !!.

One question about UIWebView…How do I clear the contents(or show a blank page) before loading another URL ?

Thanks again

Moon

Christopher Says:

January 12th, 2009 at 11:58 am

Thanks for the Tutorial. One issue though. I got everything to compile with no warnings or errors, but the only thing I get on my screen is the color gray.

Am I doing something wrong? Should this tutorial be able to run on the iPhone simulator?

Rahul Says:

January 13th, 2009 at 12:47 am

so how do you change the NSURL or the request to set the http if its not there?

Moon Says:

January 13th, 2009 at 10:59 am

Rahul: I dont know if you asked me that question ! But if Yes then i have an app where in i have list of items(each row will have a unique URL) so based on what user clicks webview(second view) will show that particular content in deatil.
I am able to do all these,but after clicking once and coming back to selction view when user clicks on another row …before displaying new link content it shows old content (for few milliseconds and then offcoz the contents of newly clicked url) I just want it to be clear before loading new content each time.

Nickel Says:

January 13th, 2009 at 11:58 am

Great tutorials.

Brandon, I have a somewhat personal question about CS at UNM do you think I could get your email so I can ask?
Thanks.

Rahul Says:

January 13th, 2009 at 2:13 pm

Moon: Well, i was asking brandon a question on how to add the http:// to the beginning of a URL if the user doesnt add it him/herself. But for what you are trying to do…when you click on a row in a table view, if you check if a self.webview==nil and then initialize a new instance of a webview and set it = to self.webview only when it is nil that would be why its happening. So if you clicked on a row and then went back and clicked on another self.webview isnt nil. Just create a new webview, set it, and release it each time…dont check if it’s nil.

brandon/anyone:default add http:// ???

Michael Says:

January 13th, 2009 at 6:36 pm

I can connect “Did End On Exit” to “I Code Browser View Controller.gotoAddress.”

However, I cannot connect “New Referencing Outlet” to “I Code Browser View Controller.addressBar.” My only option is “view.”

Michael Says:

January 13th, 2009 at 7:07 pm

I think I figured it out: I mistakenly set type of addressBar to UITextView instead of UITextField.

anonymous Says:

January 14th, 2009 at 10:28 pm

I got the program to compile and run, but my iPhone simulator screen just turns black. The view with the webpage doesn’t load for some reason. I stepped through the code in my debugger and things appear to be executing. Perhaps Christopher and I made the same mistake. Did we miss a step?

Also note that I downloaded the source code and can get that to run and load the web page. Was a critical step maybe left out of the tutorial, but was actually included in the downloaded source code?

Please reply to this post and let us know. I’m interested in learning how this works.

Jeremy White Says:

January 16th, 2009 at 11:39 am

Brando (or anyone),

I was also wandering about Ricardo Drouyn’s question:

Why did we use MainWindow.xib
instead of iCodeBrowserViewController.xib?

Thanks!
Jeremy

Rahul Says:

January 16th, 2009 at 4:39 pm

I used the view instead of the window and mine works fine. I wanted to add in some other functionality. like bookmarks.

but again…if anyone can tell me if there is an easy way to just default http:// or set it so you dont need it, thatd be wonderful :)

Brandon Says:

January 17th, 2009 at 9:45 pm

@ Nickel

it’s brandon@icodeblog.com

Jim Z Says:

January 18th, 2009 at 6:57 pm

Hello,

I also followed the same directions and all I get is a grey screen. Any ideas?

Thanks,

Jim

Moakes Says:

January 24th, 2009 at 11:38 am

Those of you who only have a black screen appear when you run the application please follow these instructions:

1.Open up MainWindow.xib in the Interface Builder.
2.Click “Window” in the “Document Window”.
3.Click “New reference outlet” and drag it onto “icodeBrowserViewController app DELEGATE” and select “view”.
4. Build and go :-)

This should sort it for you.

Chris C. Says:

January 25th, 2009 at 11:59 am

Dan, If I want my browser to show “splash.pdf” that is a .pdf contained in my App, then how would the url read in he .m file below. Instead of: NSString *urlAddress = @”http://icodeblog.com”;

Thanks.

-(void)viewDidLoad {
[super viewDidLoad];
NSString *urlAddress = @”http://icodeblog.com”;

NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[webview loadRequest:requestObj];
[addressBar setText:urlAddress];

Arg Says:

January 26th, 2009 at 2:49 am

Hey, if I’m trying to incorporate this into a project where I have RSS feeds being pulled into other tabs and organized into a table, how do I do that? I don’t even need the address bar or toolbar at the bottom (would be better to have the tab bar at the bottom like I do for the other parts of the app), I just need to be able to load up a webpage within my app

Any help is GREAT!!

Jacob Says:

January 28th, 2009 at 8:30 pm

Nice tutorial, However, I run into a problem. The application does not rotate to landscape mode. I have overrided shouldAutorotateToInterfaceOrientation as follow

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}

Any idea?
Thanks

mj Says:

January 29th, 2009 at 6:23 pm

Everything working fine except the spinning activityIndicator. Doesn’t appear….any ideas?

Chris Anthony Says:

February 2nd, 2009 at 11:46 pm

Thanks for posting this tutorial, Brandon - it’s right up my alley.

@Jacob, I’m seeing a lot of people having this problem - it seems to be a problem with a recent SDK build. I’ve seen some putative solutions that involve willRotateToInterfaceOrientation, but none of them are working for me! I’ll keep plugging away at it and see if I can come up with a better solution.

@mj, the spinning activityIndicator works for me (as of yesterday, anyway; I haven’t tried it today). Double-check and make sure that you have the connections applied correctly?

Frank Says:

February 28th, 2009 at 2:01 am

Hmmm everything works apart from the orientation and the activitymonitor for some reason… just cant figure it.

download Says:

March 3rd, 2009 at 8:07 am

hi , how r u???

Artful Dodger Says:

March 3rd, 2009 at 9:48 am

Hi there, thanks for the great tutorials. They are helping me out so much. Clicked build and go on this tutorial and got no errors. Iphone simulator opened up but then I got a black screen on the iphone sim. App did not crash back to springboard or anything. Might be doing something thats so obviously wrong but i just cant figure it out. Any help would be much appreciated.

Fred Says:

March 22nd, 2009 at 1:11 am

The picture got really small. Just copy and paste the link. Then it works ;)

iPhone development Tutorials « The Brook Song - ঝর্ণার গান Says:

March 24th, 2009 at 12:34 pm

[...] 35. Creating a web browser [...]

John Says:

April 13th, 2009 at 3:54 am

I am trying to do this with a tab based project, i cant figure out how to connect the webview. there is nothing to connect it to in the xib view. I am trying to add a web browser to a second tab in the tab based layout. that is where ther eis nothing to connect the webview to. all that is there is the “file owner”, “first responder”, and “view”. any ideas?

wiegeabo Says:

April 16th, 2009 at 11:12 pm

My app runs with no errors. But all I get is a gray screen. Nothing seems to load. Any ideas?

wiegeabo Says:

April 18th, 2009 at 2:42 pm

Ok, I figured it out.

At the end of the video, when setting the referencing outlets for the webview component, Brandon says drag a new referencing outlet to the ICode View Controller and select webview.

But he doesn’t say do it twice. Once for webview, and again for view. He shows it in the video, but just listening while flipping between windows, it’s very easy to miss.

Very sneaky Brandon. ;)

Tny Says:

April 19th, 2009 at 2:21 pm

Thanks for a great tutorial! There are a couple of features I’m trying to add to the browser - “Bookmarks” and “History”… I’ve looked everywhere and can’t seem to find an answer. Thanks again!

200ml » 100 Free courses for iPhone Dev Says:

June 28th, 2009 at 10:58 am

[...] iPhone Coding-Learning About UIWebViews by Creating a Web Browser: In this tutorial, you’ll learn about UIWebViews through the creation of a browser. [iCode] [...]

Leave a Reply