Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding WKWebView Programmatically

I am a beginner in iOS development and I have been having difficulty adding WKWebview with code. I intend to make it full width too but I get an empty screen.

var webView = WKWebView()
var activityIndicatorView: ActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad() 
     //show Activity Indicator
    self.activityIndicatorView = ActivityIndicatorView(title: "Loading content...", center: self.view.center)
    self.activityIndicatorView.startAnimating();
    self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())
    // Do any additional setup after loading the view.
    let urlString = "http://www.youtube.com";
    let request = URLRequest(url:URL(string: urlString)!)
    self.webView.load(request)
     self.view = webView
}
like image 650
bennycodest Avatar asked Sep 13 '26 08:09

bennycodest


2 Answers

let webview = WKWebView()
    webview.frame  = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100)
    webview.load(URLRequest(url: Bundle.main.url(forResource: "index", withExtension:"html", subdirectory: "subdirectories")! as URL) as URLRequest)
    self.view.addSubview(webview)

Use like this:

lazy var webView: WKWebView = {
    let wv = WKWebView()
    wv.uiDelegate = self
    wv.navigationDelegate = self
    wv.translatesAutoresizingMaskIntoConstraints = false
    return wv
}()


override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(webView)
    NSLayoutConstraint.activate([
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        webView.topAnchor.constraint(equalTo: view.topAnchor),
        webView.rightAnchor.constraint(equalTo: view.rightAnchor),
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
}
like image 38
nitin.agam Avatar answered Sep 15 '26 21:09

nitin.agam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!