iOS Tutorial – Creating a Web View (UIWebView)

Create a Web View

UPDATED for Xcode 5 and iOS7!

If your app is dependent on web content, there are a couple ways you can go about outputting that content. JSON Parsing and Web Views. We’ll be covering JSON Parsing in a later tutorial. Also, be sure to check out the continuation of this tutorial where I explain how to add a Loading Label when a web page loads.

A web view displays a website on the device’s screen. Mobile Safari is a prime example. Safari uses all kinds of bars and buttons to interact with the view. We’re not going to go into that much detail…yet. For now, we’re just going to display a web page.

Let’s begin. Unlike in the first tutorial of this series, Creating a Splash Screen, we’re actually going to be writing code in this one.

(Note: In future tutorials, we will be adding more functionality to our apps.)

1. Create a new Single View Application.

Create New Project

Single View Application

2. Name it WebView. Also select Universal, check Use Storyboard and Use Automatic Reference Counting.

WebView

Storyboard is a new way to layout you app all in one file rather than using multiple XIB files. If you do not check Use Storyboard, it’ll use the old fashioned XIBs.

Automatic Reference Counting will make it so you don’t have to manually Release or Deallocate objects in your code. It’s all done for you automatically.

3. Choose a location, and click Create.

Save Location

You’ll notice in the list of files on the left that we have (2) files called ViewController. However, they each have a different extention: .h and .m.

The .h file is the Header file (the file that tells the app what we’re going to do).

The .m file is the Implementation file (the file that does the things the header said we were going to do).

We also have (2) .storyboard files. One called Main_iPhone.storyboard, for laying out the iPhone view, and Main_iPad.storyboard, for laying out the iPad view.

4. Click on Main_iPhone.storyboard.

Click Main_iPhone.storyboard

You’ll see this to the right:

iPhone Storyboard

5. Set your buttons on the top-right so they look like this.

Screen Shot 2013-10-04 at 4.09.47 PM

On the right-bottom of Xcode, you will see a list of Objects.

Screen Shot 2013-10-04 at 4.10.42 PM

6. Scroll down until you find the Web View object.

Screen Shot 2013-10-04 at 4.11.54 PM

7. Click and drag the Web View object to our View.

Drag Web View

8. If you do not see this bar (View Controller Scene) on the left side of the edit area,

Screen Shot 2013-10-04 at 4.13.16 PM

Then click this little arrow near the bottom of your screen.

Screen Shot 2013-10-04 at 4.13.29 PM

9. In the View Controller Scene, click on Web View.

Screen Shot 2013-10-04 at 4.13.16 PM

10. At the top of the right bar, make it look like this.

Screen Shot 2013-10-04 at 4.14.59 PM

Scales Page To Fit will automatically scale the website that is inserted into the view to show the entire site rather than a zoomed in view.

Everything in the Detection section with scan the site for Links (opens a new page), Addresses (opens Maps), Phone Numbers (calls the number), and Events (adds to Calendar).

11. Repeat steps 6. thru 10. for the MainStoryboard_iPad.storyboard file. The iPad editor could be rather large, but you can zoom out my click the magnifying glass with the minus symbol on the bottom right of the editor screen.

Screen Shot 2013-10-04 at 4.16.00 PM

Next, I’m going to give you a shortcut on linking objects to your code that will save you tons of time for this and future projects.

12. Set your buttons on the top-right so they look like this.

Screen Shot 2013-10-04 at 4.16.53 PM

13. On the left bar, click on MainStoryboard_iPhone.storyboard.

Click Main_iPhone.storyboard

You should now see the iPhone edit screen on the left and the ViewController.h file on the right.

Screen Shot 2013-10-04 at 4.19.56 PM

14. While holding down the Control key, click and drag the Web View from the View Controller Scene to the ViewController.h edit screen, placing it just below the @interface line.

Drag to .h

When you release, you should see this box.

Outlet Box

15. In the name section, type in viewWeb (this could be anything you like), then click Connect.

Fill Out Fields Outlet Box

The following line of code will automatically be added in the .h file. Several other lines are automatically added to the .m file as well.

Property Added

Now we need to link the Web View on the iPad.

16. On the left bar, click on MainStoryboard_iPad.storyboard.

17. We’re going to click and drag the web view to the ViewController.h file just like we did last time, but instead of creating a new line, we going to drag to the existing line.

Drag Web View to .h

And iPad is now linked. So let’s finally write some code.

18. Change the buttons at the top right to look like this.

Standard Button Config

19. In the File View, click on ViewController.m.

Click on ViewController.m

20. In the viewDidLoad method, add the following code (in blue). The http://conecode.com can be any website you’d like.

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *fullURL = @"http://conecode.com";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_viewWeb loadRequest:requestObj];
}

NSString *fullURL = @”http://conecode.com”; We’re making a string called fullURL and setting it to the website we want our web view to load. But right now, the program thinks it’s just a bunch of text. (note the @ symbol before the quotes. You need this any time you’re setting a string with quotes.)

NSURL *url = [NSURL URLWithString:fullURL]; This tells the program that the text is actually a web address, or URL. It is now a URL object called url.

NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; This tells the program what we’re going to do with the URL object. We’re going to request the URL. It is now a request object called requestObj.

[_viewWeb loadRequest:requestObj]; Finally, we’re going to load the request into our Web View that we called viewWeb earlier.

That’s it, we’re done.

21. Now just test it by selecting iPad Simulator and then the Run button. And the same with iPhone Simulator.

Finished Product

Short and simple. In future posts, we will be adding more features to all the apps in this series of tutorials. Please let us know in the comments how things are working out for you and whether or not these tutorials are giving you a better understanding of iOS development.

You can download the source code here:  WebView Source Code

 

105 thoughts on “iOS Tutorial – Creating a Web View (UIWebView)

  1. Bob

    I’m making an app where I have a drill down table view. I used a plist to formulate the sections, and used switch and case to show the specific detail views (which have tab controllers). How would I incorporate UIWebView for the views of the tab controllers. I used http://www.iphonesdkarticles.com/2009/03/drill-down-table-view-with-detail-view.html to learn how to make a drill down table with a tab controller detail view. Also I want to use the UIWebView to view local HTML or pdf files instead of an actual website. How would I do this?

    Reply
  2. Joanna

    My Build succeeded (no issues), and then I Ran it. The simulator ran, but the screen remains “white”. I used Xcode 4.2 and iPhone Simulator 5.0. Any ideas on what the issue could be?

    Reply
    1. Cone Code Team Post author

      I haven’t tried it, yet with Storyboard. I’ll try with storyboard and let you know what the fix is. In the meantime you could try it by unchecking “Use Storyboard” when creating a new project.

      Reply
  3. Joanna

    I figured out that it is working…but the white background is in front of the website (can drag the white downward in simulator and it reveals the proper website is hidden behind it…any ideas of how to get rid of the white overlay?

    Reply
    1. Cone Code Team Post author

      When the storyboard is clicked, just to the left of the edit window there is a gray circle with an arrow pointing right, click it until you see the First Responder and View Controller boxes in tree-menu form. Then expand the View controller. You should only see inside the View Controller -> View -> Web View. If the Web View is not inside the View, You’ll see white.

      Reply
  4. Joanna

    I see View Controller>Web View>Web View. The third in the list (the 2nd ‘webview’ has the compass icon to the left of the name (same as the one in the Objects list). Perhaps the issue is that they are both named Web View?

    Reply
    1. Cone Code Team Post author

      Ah. That may be it. Delete both Web Views, then drag in a regular View, then drag in a webview on top of the View. Then do the two control drags from View Controller to webview and from webview to View Controller.

      Reply
  5. Joanna

    Ureka! I got it to work. I deleted my WebView object and found there was an extra View object under it…so started with original view controller and added Web View object and it worked. Somehow it must have had too many layers. Thanks for all of your support (and a great tutorial for me)!

    My next task to to learn how to load a URL from an NSMutableArray since there will be a different URL for each Cell in my table and array.

    Reply
  6. Neo

    i have done exactly same but my web page is not loading.I only see white screen.Though there are no errors in the code and it runs suuccessfully without any error or warnings messages.But it fails to load the webpage.
    Please somebody help me in this.

    Reply
  7. Meng

    I am using Xcode Version 4.2.1
    I am new to this. I am seeing only black screen. Also no error. I followed the fixes from the comments.

    “Delete both Web Views, then drag in a regular View, then drag in a webview on top of the View. Then do the two control drags from View Controller to webview and from webview to View Controller.”

    I am lost at doing the two control drags portion. What do I do here seeing that I got a regular View and a webview? What I did was go through step 14 to 18 again but when run still black screen.

    Appreciate some help.
    Thanks.

    Reply
  8. Meng

    I also notice that if I change the scheme (via manage scheme) such that the app is launch manually, then I am able to see the other icons in the ipad simulator, but it is saying waiting for app to launch.
    Btw.. I tried to do the above in ipad.
    But I also re-did another in iphone the same thing happens. the funny thing though is that with the device set as iphone, the simulator ran was an ipad simulator. Not sure why.

    Reply
  9. Jo

    I’m using the new version of Xcode along with a storyboard, I followed your tutorial to show a uiwebview in one of the tabs however when I ctrl an drag from my view controller to my web view I only get an outlet of view and not webView, Iv been trying to figure this out for 2 days and am completely lost. Any ideas?
    Many thanks

    Reply
  10. Luis

    I can’t see the webview either (when control dragin)

    #import

    @interface MKSMagazineViewController : UIViewController
    {
    IBOutlet UIWebView *webView;

    }

    @property (nonatomic, retain) UIWebView *webView;

    @end

    ———–
    #import “MKSMagazineViewController.h”

    @implementation MKSMagazineViewController

    @synthesize webView;

    /*
    // The designated initializer. Override to perform setup that is required before the view is loaded.
    – (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
    }
    return self;
    }
    */

    /*
    // Implement loadView to create a view hierarchy programmatically, without using a nib.
    – (void)loadView {
    }
    */

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    – (void)viewDidLoad {
    [super viewDidLoad];
    NSString *fullURL = @”http://conecode.com”;
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];
    }

    Reply
    1. Cone Code Team Post author

      In your .h file, do you have the IBOutlet for the web view?
      @property (retain, nonatomic) IBOutlet UIWebView *webView;

      (edit) Delete the IBOutlet line between the { } in the .h file.

      And in the .m file a @synthesize for that web view?
      @synthesize webView;

      After that, if you CTRL-drag from the Files Owner to the Web View, you will be able to select the webView you @synthesized.

      Hope this helps!

      Reply
  11. david

    Tried all of the comments above, can’t get the web view to come up. Running with the xib, not storyboard. When I tried with storyboard, Xcode crashed!

    Reply
  12. david

    oh, getting the following exception:
    2012-02-09 17:32:57.723 MedicalView[112:707] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “ViewController_iPad” nib but the view outlet was not set.’
    *** First throw call stack:

    However, I do, as far as I know, have everything set correctly. I’m not sure what I did wrong

    Reply
  13. seo services delhi ncr

    Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog? My blog is in the exact same niche as yours and my users would really benefit from some of the information you provide here. Please let me know if this ok with you. Thanks a lot!

    Reply
  14. Deni

    I do not have the webcontroller.xib file. I am using Xcode 4.3

    I’m new to this, and I guess I’m doing something wrong. I’ve got the other coding in. But there is no web view to attach.

    Thanks!

    Reply
  15. PBL

    Exactly what I was seeking!! How would I incorporate a timer that restarts after each screen interaction within UIWebview, and then 120 seconds after the last interaction, automatically goes back to the home page as set in NSString? Fundamentally a timeout that would go back to the weather home page defined in NSString after 120 seconds of inactivity. Using this for a home counter-top ipad weather ‘station’.

    Reply
  16. Bob Dawson

    I’m building an app where I want to use multiple web views, i.e. one is an internal html document and two others are external web pages. Your tutorial was VERY helpful getting me to the point where I can do one or the other but I’m unclear on how to have multiple occurrences. Can you provide steps to do that?

    Thanks in advance,
    –bd–

    Reply
  17. diablo 3 beta

    Hi would you mind stating which blog platform you’re working with? I’m looking to start my own blog soon but I’m having a tough time making a decision between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!

    Reply
  18. John

    Hello, I’ve tried a few tutorials on how to make UIWebview work and this is the first one that helped me get it going, so I’m very excited!

    But this only works when I use the starting screen as the webpage. What if I wanted to make links from the starting screen to another page that will have the UIWebview on it? Also, what if I have multiple page with different websites? What I’m asking, is how will the code vary in these situations? Is this a very difficult thing to do? Because I’m absolute beginner and need all the help I can get.

    Thank you very much for this post!

    Reply
  19. Mohammed

    Hi,

    I’ve done this inside a Tabbed application.

    I’m still not fully understand what I actually did, especially from step 15-18.

    How did we exactly linked the WebViewController(In my case FirstViewController) with the UIWebview ?

    Reply
  20. Krithika

    Hi…

    Will this webview not work in navigation controller??? but i need with the navigation controller!!! Could u tell me how should i do this???

    Reply
  21. Syed Adeel

    also copy this function in your view controller else it will create crashing if your view controller is popped before completion of loading the webview

    – (void)dealloc
    {
    [webView stopLoading];
    [webView setDelegate:nil];
    [webView stopLoading];
    [webView release];
    [super dealloc];
    }

    Reply
  22. Nay

    Hey , this tutorial is so good for me , bt however i need to to go my Link (server). normal if we access to my server i need to login

    do you know how to addition login process ,, because i have only white screen because it didn’t show login page

    Reply
  23. akash

    Hi , I have to create a web view component which contains a html file. Any request generated from this page will invoke a javaScript file which will invoke native code and in the same way the flow will come from native code to javaScript and to web view. Till displaying html file I have worked out but sending request and getting response via a javaScript file not getting any idea. Can anyone help me in this. It will be highly appreciated for this help. with thanks from sabya.

    Reply
  24. akash

    I am creating a iPad application. I have to create a web view component which contains a html file. Any request generated from this page will invoke a javaScript file which will invoke native code and in the same way the flow will come from native code to javaScript and to web view. Till displaying html file I have worked out but sending request and getting response via a javaScript file not getting any idea. Can anyone help me in this. It will be highly appreciated for this help. with thanks from sabya.

    Reply
  25. stoney

    Great tutorial, thanks.
    I wanted to add a text field to display the URL, and allow a URL to be typed in. I can’t figure out how to do this. When I cntrl-click and drag from the text field to the web view, I was looking for takeStringURLFrom, but it’s not there. How can I make it be there. Or how can this be done in another way? Thanks again.

    Reply
  26. Jay

    Man..this works on the old xcode versions. New ones no so much. I did build an app on a really ancient xcode with this but they all crash on ipads. You should definitely redo this tutorial right here..nobody and I mean nobody else has a complete one so you’d definitely be a standout with it.

    Reply
  27. Jay

    Thanks for the update, I tried it and it looks fine..no real issues on the build but I do end up with blank screens in the ios simulator and it fails to launch on my device when i try to build it for device. Get the icon on my ipad but no launch at all. I do see this message when I launch it in simulator.

    Error message:

    Application windows are expected to have a root view controller at the end of application launch

    Reply
  28. Jay

    I figured it out..the issue I was having was that I added a navbar and buttons..i followed the same old commands for back and reload..I think this may have changed and isn’t covered here but removing the entire nav bar and recreating the webviews worked. Great tutorial Cone Code team..hands down the only tutorial online worth it’s weight in screen space..

    Reply
  29. Joey

    this tutorial is awesome! its the only one that assists Xcode 4.4.1 with a UIWebView lesson that actually is taught with clarity and understandable, brief explanations. I will recommend this to people

    Thanks, again mate!

    Joey

    Reply
  30. Jay

    Hey guys, I submitted this app to modmyi for cydia’s repo it works when I launch it on my device but not on anyone else’s. I’ve shut off codesigning everywhere on the app..can you recommend anything for myself and any others facing this issue. The app opens and instantly shuts down..

    Reply
  31. Tim Suchanek

    I love you!! This tutorial really rocks! I’ve looked for it a long time, xcode had many changes and the old tuts didn’t work at all! This was my first App on iPhone ever and it was really understandable for a newbie like me!!

    The world needs people like you. Because in the apple reference, I didn’t find such a well documented basic tutorial.

    Thanks!

    Reply
  32. Josh

    Great tutorial! I just worked through it, and at the end it told me it needed an underscore before viewWeb -> [_viewWeb loadRequest:requestObj]; But I had named my UIWebView viewWeb just like you did. Does anyone know why it told me it needed that?

    Reply
  33. Anthony De Souza

    @Josh I had the same issue and as a newcomer to iOS development I can share the following discovery:

    “When you see code that uses a variable that is prefixed with an underscore, you know right away it is an ivar (an object instance variable) and not a local variable.”

    if you add the following to the .h file then it would work as the article shows (without the _ prefix)

    @synthesize viewWeb;

    it seems different versions of xcode require/don’t require the @synthesize. I have xcode 4.51 and am got the warning to change the property name to the _ version.

    From what i can make out it is better to use the _ version to denote ivars so that your code is more understandable – but its just a naming convention.

    For more info see
    http://stackoverflow.com/questions/11459320/property-declaration-in-objective-c

    Reply
  34. Don Morris

    Very detailed explanation of some basic concepts for novices. Thanks! Why is it that variables are prefixed with ‘*’?

    Reply
  35. Scott

    This is an excellent tutorial! I particularly like the step by step explanation of what the lines of code mean. I am using Xcode 4.5.2 and I had the same issue Josh had with the program indicating I needed to change viewWeb to _viewWeb. I just hit return and it was replaced for me and the program ran.

    I am also trying to use UIWebView to display .pdf and .doc documents that are native on the app. I would appreciate any suggestions on how to do that.

    Thanks again for a great tutorial!

    Reply
  36. Montana

    You missed something.

    [viewWeb loadRequest:requestObj]; will return a compiler error. It should be [_viewWeb loadRequest:requestObj];.

    Reply
  37. jebrum

    This works very well, but could you make a guide showing how to do this with https websites using a self signed certificate?

    Reply
  38. darrick

    love the tutorial… but will the App get rejected if it doesnt contain a loading feature? just wondering, i heard that some place b4.

    thanks again.

    Reply
  39. Pingback: iOS How To – Adding a Loading Label to a (UIWebView) | Cone Code Development

  40. Rana Hamad Khan

    i m making app with few html pages .my web view not show my entire html pages my images not show fully ,i mean i m unable to scroll horizontal ,although my vertical scroll working good .
    help me please…..
    i have done the above procedure but still faces tha same problem….

    Reply
  41. Pingback: Nice iOS WebView Tutorial | Adventures in tech

  42. Pingback: Multiple UIWebView

  43. Leonardo

    Hello, thanks a lot for the tutorial really helpfull! I have made this application but now i have i problem with the other tutorial “Adding a Loading Label to a (UIWebView)” . I’m stop at point #16 “16. Add the following piece code to the end of the @interface line: <UIWebViewDelegate>”

    I don’t understand where i can write those string; can you help me please? It’s my first application in xcode :)

    Can you release the source of this second tutorial “http://conecode.com/news/2013/03/ios-how-to-adding-a-loading-label-to-a-uiwebview/” ?

    Thnaks a lot and sorry for my english.
    Leonardo

    Reply
  44. Greg

    This is such a good tutorial – really simple, clear and easy to use. Thanks!!!!
    The universal Deployment Target that works for me is 5.0 and 5.1 but
    I’d like to be able to run it in iOS 6.0 or higher. Is there a way to do this ?

    Reply
  45. Pingback: No visible @interface 'UIView' declares the selector 'loadRequest' - iPhone Solutions - Developers Q & A

  46. Pingback: Adding a UIWebview to a second Storyboard | Developers Questions - Msn4Free.com

  47. Kallin Jo Newman

    does this work with Xcode 5 because step 14 won’t work for me. when i release it no box shows up. it might be because UIViewController is not purple but i don’t know how to fix that

    Reply
  48. Asif

    This is really nice post.
    This is actually that i am looking for i have follow the instruction posted in the tutorial
    and got it.

    Thanks

    Reply
  49. Lionel

    Hi really nice tutorial,code runs well
    but when i click on the News tab
    i cant scroll to the bottom of page any ideas how to fix that?
    as this page got more content than the others.

    Thanks

    Reply
  50. Harvey

    Does anyone have any guides to on creating the Web View in landscape?

    Following the helpful steps above I have created an application pointing to my
    website, however when I rotate my device into a landscape orientation the website
    remains in in portrait and there is a white blank filler on the right of the view.

    The website opens fine in landscape on Google Chrome and Safari on the iPad.

    I have tried to restrict the app to landscape only, but it is appearing the same.

    Any ideas would be really helpful.

    Thanks,
    Harvey

    Reply
  51. mishi

    Hi I am able to load and run a web page in my app. however, i m unable to scroll the page. plz help. i even tried using the scroll view within my app. it’s not working.
    please help! thanku in advance :)

    Reply
  52. Hal Gatewood

    Thank you for this! Do you know how to incorporate ‘shouldStartLoadWithRequest’ with the WebView so that we can intercept pages being called in the webview?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


eight + = 15

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">