How To Fix Swift WKWebView Do Not Load URL Page Error

WebKit.WKWebView class is used to implement a micro web browser in iOS app or Mac OS app. It provide several method to load html url page, local html file etc. But when i use it to load and display 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 investigate i finally find the method to fix it.

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

Below is the source code to load a web page by http url. When i run it, it only display 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)

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 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.

  1. Click the Xcode project’s Info.plist file to open and edit it.
  2. Then click the plus button at the end of Information Property List item to add one property item.
  3. Choose App Transport Security Settings item from the new item drop down list.
  4. Click the plus icon at the end of this newly added item.
  5. 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
  6. Now when you run your app, you can see the WKWebView object display the specified web page url.
  7. If you right click the Info.plist file, and click Open As —> Source Code menu, it will display the xml version of Info.plist file. You can find that it add below xml content in Info.plist source code.
    <key>NSAppTransportSecurity</key>
    <dict>
         <key>NSAllowsArbitraryLoads</key>
         <true/>
    </dict>
READ :   How To Set iOS UIView Background With Customized Color Or Image In Swift

Leave a Reply

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.