Search code examples
iosswiftwebkitwkwebview

iOS - [WKWebView .cxx_construct] must be used from main thread only


I am new to iOS development.

I followed this tutorial: https://www.ioscreator.com/tutorials/webview-ios-tutorial-ios11 to create application with web view. It worked fine, but suddenly stopped and I have no idea what is different.

Now the application is crashing saying: [WKWebView .cxx_construct] must be used from main thread only in this code (first line of function):

override func loadView() {
    viewerWebKit = WKWebView()
    viewerWebKit.navigationDelegate = self
    view = viewerWebKit
}

What is causing this problem? Why did it work fine before? And why did it suddenly stop working?


Solution

  • @lokesh's answer is in the right direction, but the wrong solution. loadView() appears to be called on a non-main thread. This should never happen. One cause would be that you're calling loadView() manually (which you should never do). Another is that you're referencing view on a background thread, which you should also never do. (This is the one I suspect you're doing.)

    Place a breakpoint in loadView before the crash. Run the program, and make sure it's on the main thread. In the call where it isn't, trace backwards to where you're invoking it incorrectly. You should not resolve this by dispatching to the main queue in loadView, but you will probably need to add a similar call somewhere else.