UIWebView and UIWebViewDelegate example in Swift

In this video tutorial I am showing how to create a new UIWebView and how to load information into it in three different ways:

1. Load a web page from a remote URL
2. Load short HTML string
3. Load html file stored which is a part of your mobile app.

Also I am showing you how to add UIActivityIndicator to let user know that web page started loading and stop activity indicator animating when web page has finished loading.

Another nice to have example in this video is a Refresh button. I am showing you how to add a refresh button which when tapped will refresh the web page and load its content again. This is sometimes needed because internet connection is not always fast and sometimes web pages load partially only and it is good to be able to reload the page.

I hope this video tutorial is helpful to you guys and if it does not work for you for some reason, please drop me a line.

Thank you!

 

Source code


//
// ViewController.swift
// MyWebViewExample
//
// Created by Sergey Kargopolov on 2015-03-14.
// Copyright (c) 2015 Sergey Kargopolov. All rights reserved.
//
import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var myWebView: UIWebView!
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

myWebView.delegate = self

//1. Load web site into my web view

let myURL = NSURL(string: “https://www.swiftdeveloperblog.com”);
let myURLRequest:NSURLRequest = NSURLRequest(URL: myURL!);
myWebView.loadRequest(myURLRequest);

/*
//2. Load html string into web view

let htmlString:String = ”
Bold string
myWebView.loadHTMLString(htmlString, baseURL: nil)
*/

/*

//3. Load local html file into web view
let myProjectBundle:NSBundle = NSBundle.mainBundle();

let filePath:String = myProjectBundle.pathForResource(“my-html-file”, ofType: “html”)!

let myURL = NSURL(string: filePath);
let myURLRequest:NSURLRequest = NSURLRequest(URL: myURL!);

myWebView.loadRequest(myURLRequest)
*/

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func webViewDidStartLoad(webView: UIWebView)
{
myActivityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView)
{
myActivityIndicator.stopAnimating()
}

@IBAction func refreshButtonTapped(sender: AnyObject) {
myWebView.reload()
}

}