Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView not displaying website (Swift 4, iOS 11, Xcode 9.3)

For some reason, the WKWebView in my app won't display any websites like "https://www.google.com.au". I have tried changing the "Allow Arbitrary Loads" to "YES" in info.plist but that didn't resolve the issue.

PLEASE HELP!!!!! Thanks

My Code:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        displayWebPage()
    }

    private func displayWebPage() {
        let url = URL(string: "https://www.google.com.au")
        let request = URLRequest(url: url!)
        webView.load(request)
    }
}

Screenshot of StoryBoard: StoryBoard

like image 523
Matthew Cho Avatar asked Apr 06 '18 02:04

Matthew Cho


2 Answers

Connect the WKNavigationDelegate, this will fix the webpage not loading try the below code. Any errors thrown while loading the webpage will be printed in the webViewDidFail delegate.

class ViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        displayWebPage()
    }

    private func displayWebPage() {
        let url = URL(string: "https://www.google.com.au")
        let request = URLRequest(url: url!)
        webView.navigationDelegate = self
        webView.load(request)
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(error)
    }
}
like image 54
BXV Avatar answered Nov 03 '22 15:11

BXV


set webView delegates.

    webView.UIDelegate = self
    webView.navigationDelegate = self

and also try by adding your domain in exception domain list

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>google.com.au</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>
like image 2
Ajay saini Avatar answered Nov 03 '22 14:11

Ajay saini