6

In my code, I have a part that creates a new WKWebView with a specific WKWebViewConfiguration, which in turn has a WKPreferences reference. All of this then gets added to the view of the application.

The problem is that up until this point, my code has been running perfectly, with no problems.

Now, for some bizarre reason, when I launch the application, I get

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeec686fc0)

on the line when I create a variable for the WKPreferences.

I am working with Xcode 10.1, Swift 4, and I have Alamofire and NetworkReachability pods installed. I have tried just creating the WKWebView without the WKPreferences, but the error just moves on to the WKWebViewConfiguration instead.

func createWebView() {
    let preferences = WKPreferences()   //<-- EXC_BAD_ACCESS
    preferences.javaScriptEnabled = true
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.preferences = preferences
    webConfiguration.allowsInlineMediaPlayback = true
    webViewVar = WKWebView(frame: self.view.bounds, configuration: webConfiguration)
    webViewVar.uiDelegate = self
    self.view = webViewVar
}

override func loadView() {
    createWebView()
}

The expected behavior is that the app would launch and show a web page, that doesn't change, specified elsewhere in the code. The actual result is that the app crashes with the EXC_BAD_ACCESS error upon startup.

4

1 回答 1

7

我不得不说你发现了一个错误。出于某种原因,运行时不允许您在应用程序生命周期的早期创建 WKPreferences 对象。

解决方法是您必须推迟 Web 视图的创建,直到应用程序启动并运行。为此,请改为删除loadView并实现viewDidLoad,并在那里完成所有工作,使 Web 视图成为主视图的子视图,而不是试图使其成为主视图。

var webViewVar : WKWebView!
func createWebView() {
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.preferences = preferences
    webConfiguration.allowsInlineMediaPlayback = true
    webViewVar = WKWebView(frame: self.view.bounds, configuration: webConfiguration)
    webViewVar.uiDelegate = self
    self.view.addSubview(webViewVar)
    webViewVar.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
override func viewDidLoad() {
    super.viewDidLoad()
    createWebView()
}

这很烦人,你应该向 Apple 提交错误报告,但至少这会让你暂时继续前进。

于 2018-12-27T02:45:26.210 回答