iOS – Embedding Web Pages

This short post is a tutorial on how to embed a specified webpage on the screen using the UIWebView class. This class includes several methods to load web content and several properties to control how the web page is displayed inside the window.

The screenshot shows a simple example where I embed the exact same web page (http://www.joshiscorner.com) in two different UIWebView objects:

Screen Shot 2014-05-19 at 11.43.17 AM

STEP 1: Set up the storyboard

Drag two UIWebView objects to the storyboard and size both views to be 280 by 250.

STEP 2: Make connections

Make IBOutlet connections by ctrl-clicking from the UIWebViews on the storyboard to the ViewController interface.

STEP 3: Specify the URL and display it inside the window

The ViewController implementation is copied below.

As usual, we synthesize the two UIWebView properties and then use the NSURL class to specify the URL we wish to load. In this case, we load the same URL in both the windows. But in the top window, we load the page “as is”, that is using the width specified in the HTML/CSS on the remote server. In this case, the width of the page is set to 970px, while the width of the iPhone screen is 320px. So when we display the page “as is”, only a fraction of the content is seen inside the window.

In the second view, we use the “scalesPageToFit” property of the UIWebView object and set it to YES. This forces the view to display the entire width of the web page.

You can learn more about the UIWebView class on the Apple Developer website.

Leave a Reply

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