Loading a Website with UIWebView

In iOS you can load a URL into a native app through the UIWebView Control.

Update: July 9, 2014. This tutorial is made with Xcode 4 and targeted for iOS 6. The rewritten version in Swift for iOS8 and Xcode 6 is available here.

Let's create a new Project with the "Single View Application" template.

Use the following Project Options:

Go to the storyboard View and drag a WebView from the Object Library on top of your main View.

Select the Assistant Editor to reveal ViewController.h,Ctrl-Click From your UIWebView and drag to ViewController.h between the @interface and @end directives.

This will create the following code in ViewController.h

@property IBOutlet UIWebView *myWebView;

and in ViewController.m


@synthesize myWebView;

Now modify the ViewDidLoad method in ViewController.m


- (void)viewDidLoad 
[super viewDidLoad];

NSString *urlString = @"http://ioscreator.com";

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
if ([data length] > 0 && error == nil) [myWebView loadRequest:request];
else if (error != nil) NSLog(@"Error: %@", error);
  1. Create a NSString which contains our URL
  2. Convert our string to a NSURL object.
  3. Place our URL in a URL Request.
  4. Create a operation queue to handle the asynchronous request
  5. The request will be asynchronous, because it can take some time to ttansfer the website. With this method the request will not block the Main Thread. The completionHandler uses a block to handle the reponse. When the response succeeds the website will be showed, otherwise an error will be displayed.

You can download the source code of  ViewWebSite at the ioscreator repository on github.