Create UIWebView Programmatically and Load Webpage Using URL

The Swift code example below demonstrates how to create a UIWebView programmatically and how to load a webpage using the URL.  If we look at the below code example in details, it will also show how to:

  • Create UIWebView programmatically,
  • Implement the UIWebViewDelegate functions like the webViewDidStartLoad and the webViewDidFinishLoad
  • Make UIWebView load a webpage from a remote URL.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Creating the UIWebView Programmatically

import UIKit
import WebKit
class ViewControllear: UIViewController, WKUIDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let myWebView:WKWebView = WKWebView(frame: CGRect(x:0, y:0, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height))
        myWebView.uiDelegate = self
        self.view.addSubview(myWebView)
        
        
        //1. Load web site into my web view
        let myURL = URL(string: "http://www.swiftdeveloperblog.com")
        let myURLRequest:URLRequest = URLRequest(url: myURL!)
        myWebView.load(myURLRequest)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

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

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!