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.

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.


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:

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.
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.
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:

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.

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:

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:

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!


79 Comments
Is there anyway to emulate the tap-status-bar to scroll to top? because in the current state it doesn’t work. May be another tutorial?
Dude. Some minor enhancements:
+ use a dynamic spacer between the buttons on the lower toll bar.
+ connect the back/forward buttons directly to the goBack and goForward methods on the view! way simpler. Plus you get the original NeXTStep awesomeness of the true target/action paradigm. No middle man of your own custom class – just wire up the functionality.
Dude! .
here’s a code correction or possibly just a suggestion. I had to use a different name for my NSURL. Though, at the same time I also put the URL inside the brackets in uppercase. That probably fixed it. Anyhow, the suggestion to icodeBlog and anyone else is to not use variable names that are too similar to Apple’s types. It’s generally frowned upon in other programming languages and usually impossible too. Xcode allows it because it is case sensitive.
NSURL *destURL = [request URL];
[iboTxtAddressBar setText:[destURL absoluteString]];
I’ve tried to implement autorotation within your code, but I can’t get it to work, do you know why? I set the autorotation to “return YES;” — no compile errors or SIGBRT encountered. Just no response in either the simulator or my hardware.
Any help would be appreciated.
Thanks…
Hi buddy,
Thanks for the tutorial.
Learned about the ‘WebView’ better.
Good Post, the only thing is that my GO BACK and FORWARD buttons doesn’t work.
Ay idea.
Someone asked earlier how to clear the webview between requests. Here’s how I did it:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
Sussed out the orientation problem that people have been having.. when interface builder loads up double click on iCodeBlogViewController and build the browser in the view controller window that appears. Building it there instead of in the window seems to work..
Hi,
Thanks for your tutorial, and now I have a question, how to display the correct address after pressing “back” or “forward” button?
Thanks for the great tutorial. I’m sure you’re too busy to answer all of these questions so I thought that I’d post some answers that may not be as elegant as yours…
- How to ensure that url starts with “http://”…
At the top of the gotoAddress method, add this code:
// make sure url starts with “http://”
if (! [addressBar.text hasPrefix:@"http://"]) {
[addressBar setText:[NSString stringWithFormat:@"http://%@", addressBar.text]];
}
- how to update the addressBar after clicking go forward or go back:
Make your webViewDidFinishLoad method look like this:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[addressBar setText:self.webView.request.URL.absoluteString];
[activityIndicator stopAnimating];
}
If your “webViewDidStartLoad” doesn’t work –
try to add this
webView.delegate = self;
Great Tutorial, finally one that demon straights the activity indicator!
I have one problem though, when using your project im not able to rotate the application..
Ive tried Return YES;
&
(interfaceOrientation == UIInterfaceOrientationLandscapeRight)
But still not luck, please help
Thanks for not even attempting to contact me
Great done and keep posted. Looking forward to reading more from you.
Hello
The compiler says “Nested functions are disabled, use -fnested-functions to re-enable” at lines
- (void)viewDidLoad {
[super viewDidLoad];
NSString *urlAddress @”http://google.com”;
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[addressBar setText: urlAddress];
}
Any help appreciated!
Regards,
modder
This error usually means you made a typo. In this case:
you forgot a ‘=’ right in front of ‘@”http://google.com”‘.
Cheers,
Jr
hey,
can u tell how to open 192.168.1.1
great tutorial. I’m a noob and have gotten some pretty good results but…
has anyone run across this in version 3.2.2:
when i implement the viewDidLoad code to have a startup page, the app launches then immediately shuts down (ipad version).
anyone with any thougths?
can u please tell me how did u implemented that white light when user taps on Address.
All I want is a simple example of loading a web page via the web view control…no address bars, no buttons…just load a page when app is launched. I’m getting really frustrated with using Xcode…using Visual Studio is very straight forward…add a component, click on it, write your code…this jumping through hooping is really frustrating…create a wheel and put it over here…now put a button on the form, jump three times, recite Hamlet and bury the dog bone in the backyard….etc.
Any help is greatly appreciated.
Thanks,
Malin
Thanks for posting this tutorial. I was looking for exactly what you posted here.
Thanks!
It operates correctly.
But I need to get a content of specific address in html format.
What do i do? Please help me.
I run 3.1.3 and 3.2. Both version works. 3.2 call iPad simulator but everything works the same. Of course the UIWebView is showing iPhone size and UIWebView didn’t scratch out or size up to fit iPad screen 1024×768.
I do encounter this warning. I couldn’t figure out how to remove this warning. I suspect it is related to how objects are connected in Interface Builder.
/Users/XXX/ApplicationIphone/browser/MainWindow.xib:10:0 ‘Browser View Controller’ has both its ‘NIB Name’ property set and its ‘view’ outlet connected. This configuration is not supported.
In my case webViewDidStartLoad and webViewDidFinishLoad are never called.
I’ve created: Files Owner, First Responder, View (Navigation Bar (Navigation Item – title (btnWebBack, btnWebForward)), webView), MyViewController.
They are linked as shown below:
MyViewController: view – View, webView – webView
webView: delegate – Files Owner, goBack – btnWebBack, goForward – btnWebForward, webView – MyViewController
View: view – Files Owner/MyViewController
Files Owner: view – View, delegate – webView
My interface looks like:
@interface MyViewController : UIViewController
{
}
In my case webViewDidStartLoad and webViewDidFinishLoad are never called.
I’ve created: Files Owner, First Responder, View (Navigation Bar (Navigation Item – title (btnWebBack, btnWebForward)), webView), MyViewController.
They are linked as shown below:
MyViewController: view – View, webView – webView
webView: delegate – Files Owner, goBack – btnWebBack, goForward – btnWebForward, webView – MyViewController
View: view – Files Owner/MyViewController
Files Owner: view – View, delegate – webView
My interface looks like:
@interface MyViewController : UIViewController
{
IBOutlet UIWebView *webView
}
@property (nonatomic, retain) IBOutlet UIWebView *webView;
-(IBAction)goForward:(id)sender;
-(IBAction)goBack:(id)sender;
@end
I synthesize the webView in my implementation file and include the methods webViewDidStartLoad and webViewDidFinishLoad but neither the first nor the second one is called. I’ve tested with NSLog()
I think you need to set webview’s delegate to file owner
Awesome. Great thanks!!
thanks,it easy to understand for new iphone developer. thanks again
I have a webview as part of a tabbed application. The web view loads the page but the webViewDidFinishLoad never fires and the activityIndicatorView never goes away.
I have it set up like the tutorial but I can’t seem to make the activityIndicatorView work. Any help is greatly appreciated.
Thanks for the great tutorial.
10 Trackbacks
[...] Original unknown [...]
[...] 35. Creating a web browser [...]
[...] 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] [...]
[...] 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] [...]
[...] UIWebView Video page_revision: 11, last_edited: 1253902141|%e %b %Y, %H:%M %Z (%O ago) edittags history files print site tools+ options edit sections append edit meta who watches backlinks view source parent block rename delete help | terms of service | privacy | report a bug | flag as objectionable Hosted by Wikidot.com — get your free wiki now! Unless stated otherwise Content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License [...]
[...] 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] [...]
[...] 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] [...]
[...] 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] [...]
[...] Attacking each piece one at a time The first item of attack is UIWebView. This looks like a good tutorial to begin with. [...]
[...] in iPhone SDK iCodeBlog has a nice tutorial on how to make a web browser in iPhone SDK. iPhone Coding – Learning About UIWebViews by Creating a Web Browser | iCodeBlog Hope this helps MozyMac Founder,Chairman and CEO MacBook Pro Unibody late 2008 2.4Ghz [...]