Mono

Using C# to Develop for iPhone, iPod Touch and iPad

Brian Long Consultancy & Training Services Ltd.
March 2011

Accompanying source files available through this download link

Page selection: Previous  Next

Web Browsing with UIWebView

Letís get the web browser page under way. The ingredients for this include a Navigation Bar (UINavigationBar) with a Bar Button Item (UIBarButtonitem) placed on it, both found in the Windows, Views and Bars subset of Objects on the Library window. We also need two Round Rect Buttons (UIButton), a Text Field (UITextField) and a Web View (UIWebView), the last of which is in the Data Views subset of Objects. They can be laid out according to the Interface Builder screenshot below, which is followed by an image of the target application page running (remember that the top navigation bar there comes from the main window). The Navigation Bar button can have its image selected by its Identifier attribute.

Browser app in Interface BuilderBrowser app running in the Simulator

Outlets will need to be set up for some of these controls so we can access them at runtime. In the case of a page based on a UIViewController youíll see the controls you add to the page under the View in the Document Window. The outlets need to be added to the BrowserPage object, which can be selected on the Document Window as Fileís Owner. The screenshot below shows the names of the five new outlets. It should be mentioned that the button outlets are only being added so event handlers can be set up using anonymous method syntax instead of setting up actions in Interface Builder, which would necessitate implementing the action method to house the event handler code.

Browser app in Interface Builder

The idea of the UI controls is for the left and right arrow to be Back and Forward history navigation buttons, and for the Button on the lower Navigation Bar to refresh the current page. The Text Field is meant to be the same as a browser address bar, so use the Attributes Inspector to set the Keyboard attribute to URL and the Return Key attribute to Go.

Notice on the top Navigation Bar (in the running app) there is a button to take you back to the main page.

The implementation of this page is fairly simply. When the view loads the various UI controls need initializing and a default web page is loaded:

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    InitButtonsAndTextField();
    InitBrowser();
    //Load a default page
    LoadPage("flickr.com");
}

Helper functions are used for all these jobs. The initialization functions set up events for the controls. The Buttons are trivial; they simply call corresponding methods in the UIWebView. The Text Field ShouldReturn property ensures the keyboard will close when Go is pressed, as weíve seen before, but also then loads the URL that was entered into the field.

private void Alert(string caption, string msg)
{
    using (UIAlertView av = new UIAlertView(caption, msg, null, "OK", null))
    {
        av.Show();
    }
}
 
private void InitButtonsAndTextField()
{
    backButton.TouchUpInside += (s, e) => { webBrowser.GoBack(); };
    fwdButton.TouchUpInside += (s, e) => { webBrowser.GoForward(); };
    refreshButton.Clicked += (s, e) => { webBrowser.Reload(); };
    urlField.ShouldReturn = (textField) => 
    {
        LoadPage(textField.Text.ToString());
        return textField.ResignFirstResponder(); //Hide keyboard 
    };
}
 
private void InitBrowser()
{
    webBrowser.LoadStarted += (s, e) => 
    {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
    };
    webBrowser.LoadFinished += (s, e) => 
    {
        urlField.Text = webBrowser.Request.Url.AbsoluteString;
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
    };
    webBrowser.LoadError +=  (s, e) => 
    {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
        Alert("Browser error", "Web page failed to load: " + e.Error.ToString());
    };
}

The web browser control also has event handlers set up, with the main purpose of activating and deactivating the network activity indicator on the iPhone status bar (which oddly is not an automatic response to network activity) and also that reports any navigation errors in an alert.

Additionally, when a web request has finished loading a page it may ultimately resolve to a different URL than was requested. This is very common on mobile devices as pages redirect to a mobile-specific version. The LoadFinished event handler reflects the final URL back to the Text Field.

The remaining method is LoadPage(), which ensures the required http:// prefix is present in the URL and then builds an NSUrlRequest from an NSUrl and passes it to the UIWebViewís LoadRequest() method.

private void LoadPage(string url)
{
    if (url != "")
    {
        if (!url.StartsWith("http"))
            url = string.Format("http://{0}", url);
        webBrowser.LoadRequest(new NSUrlRequest(new NSUrl(url)));
    }
    //Show the URL that was requested
    urlField.Text = url;
}

And there we have the fully working web browser shown earlier that defaults to displaying http://flickr.com (which is then redirected to the mobile version of Flickr).

Go back to the top of this page

Go back to start of this article

Previous page

Next page