Migrate UIWebView to WKWebView

14,011

Add "WebKit" framework to your class.

Please refer the below code

import UIKit
import WebKit

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let myWebView:WKWebView = WKWebView(frame: CGRectMake(0, 0,   UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))

        myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.communionchapelefca.org/app-home")!))
        self.view.addSubview(myWebView)

    }
}
Share:
14,011
Greg Williams
Author by

Greg Williams

Updated on July 01, 2022

Comments

  • Greg Williams
    Greg Williams almost 2 years

    Within my iOS app I am attempting to migrate my old UIWebView code to WKWebView since WKWebView is, in theory, faster and more efficient than UIWebView.

    I have looked at a bunch of tutorials (like here and here and here) on the internet but cant find anything that explains how to simply add a WKWebView to my app progmatically.

    Can someone point me to a simple tutorial or explain in the comments how to convert this code to WKWebView progmatically? thanks in advance.

    View Controller.swift:

    import UIKit
    
    class ViewController: UIViewController, UIWebViewDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    
            myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.communionchapelefca.org/app-home")!))
            self.view.addSubview(myWebView)
    
  • Greg Williams
    Greg Williams about 8 years
    that worked; thanks! I feel like an idiot that it was so simple to change/adjust to WKWebView.
  • Leo Dabus
    Leo Dabus about 8 years
  • Carlos Irano
    Carlos Irano over 6 years
    Just a note: needs use NSAppTransportSecurity with NSAllowsArbitraryLoads in info.plist to works.
  • royalmurder
    royalmurder over 5 years
    @CarlosIrano That's only needed whilst using an HTTP url - and if that specific url is all that is needed, it can be whitelisted instead of enabling NSAllowsArbitraryLoads ;)
  • Jurgen Dictus
    Jurgen Dictus over 3 years
    FYI myWebView.loadRequest is now replaced with myWebView.load