How To Fix Swift WKWebView Do Not Load URL Page Error

WebKit.WKWebView class is used to implement a micro web browser in the iOS app or Mac OS app. It provides several methods to load Html URL pages, local Html files, etc. But when I use it to load and display the Html page in iOS version 9 and later, I find it can not display the Html page. I can only see a blank screen that is whole white without the web page. My Xcode version is 11. After some investigation, I finally find the method to fix it.

1. How To Fix WKWebView Load Request Return Blank Page Error.

  1. Below is the source code to load a web page by HTTP URL. When I run it, it only displays a blank page.
    // WKWebView exist in WebKit package. 
    import WebKit
    
    // Create an instance of WKWebView.
    var webView: WKWebView!
    
    webView = WKWebView()
    
    // Create a URL object with provided url. The url is http protocol.
    let url:URL? = URL(string: "http://www.google.com")
            
    // Create a URLRequest object with above url.
    let request:URLRequest = URLRequest(url: url!)
            
    // Load above url request, it should display the specified url page content in the WKWebView object, but in this example it only display a blank page.
    webView.load(request)
  2. This is because when you load the URL http://www.google.com, Google will redirect the request to it’s HTTPS version as https://www.google.com. So to load the HTTPS protocol web page URL, you should edit the Xcode project’s Info.plist file. And add App Transport Security Settings —> Allow Arbitrary Loads item in it like below.
  3. Click the Xcode project’s Info.plist file to open and edit it.
  4. Then click the plus button at the end of the Information Property List item to add one property item.
  5. Choose App Transport Security Settings item from the new item drop-down list.
  6. Click the plus icon at the end of this newly added item.
  7. And select Allow Arbitrary Loads item from the drop-down list. And select value YES for this newly added item.
    xcode-project-Info.plist-app-transport-security-settings-allow-arbitrary-loads
  8. Now when you run your app, you can see the WKWebView object display the specified web page URL.
  9. If you right-click the Info.plist file and click Open As —> Source Code menu, it will display the XML version of the Info.plist file. You can find that it adds below XML content in the Info.plist source code.
    <key>NSAppTransportSecurity</key>
    <dict>
         <key>NSAllowsArbitraryLoads</key>
         <true/>
    </dict>

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.