如何防止 WKWebView 对象崩溃?

How do I keep a WKWebView object from crashing?

场景

我正在 Swift 中构建一个 iOS 应用程序。其中一项功能是将实时视频源作为应用程序背景。视频提要来自使用 sudo motion 的本地网络上的 Raspberry Pi。 Motion 已成功在默认端口 8081.

上托管提要

Swift 应用程序有一个 WKWebView 对象,源指向我的 Raspberry Pi 的运动端口。

疑似问题

端口8081的网页不断刷新以从相机加载最新帧。

问题

当 运行 应用程序时,提要连接成功并加载第一帧,偶尔加载第二帧但随后中断。

有几次我在终端中收到以下错误:[ProcessSuspension] 0x282022a80 - ProcessAssertion() Unable to acquire assertion for process with PID 0 让我相信这是一个与网页不断刷新的性质相关的内存管理问题。

当前配置

目前,我对 WKWebView 对象的 .load() 调用在 ViewController.swift > override func viewDidLoad().

提议的决议

我是否需要构建某种形式的循环结构,在其中加载帧、暂停执行然后调用 WKWebView 以在几秒后重新加载新帧。

我是 Swift 的新手,非常感谢您耐心等待我的问题格式。

WkWebView 和运动加载在 Xcode 9 和 iOS 11 版本中有效,但似乎不再适用于 iOS 12。你是对的,webkit 正在崩溃在第二张图片上。

由于您是 Swift 的新手,我建议您阅读有关代表的 link,因为我提供的这个解决方案对您来说更有意义。 Swift Delegates 总之,"Delegates are a design pattern that allows one object to send messages to another object when a specific event happens."

有了这个 solution/hack 我们将使用几个 WKNavigationDelegates 在 WkWebView 执行特定任务时通知我们并注入我们对问题的解决方案。您可以在此处找到 WKWebKit 的所有委托 WKNavigationDelegates.

下面的代码可以用在一个全新的iOS项目中,替换掉ViewController.swift中的代码。它不需要界面构建器或 IBOutlet 连接。它将在视图上创建一个单一的 web 视图并指向地址 192.168.2.75:6789。我包含了内联注释以试图解释代码的作用。

  1. 我们正在从 decidePolicyFor navigationResponse 委托中的运动加载 HTTP 响应两次,并使用计数器进行跟踪。我留下了一些打印语句,因此您可以看到响应是什么。第一个是header,第二个是图像信息。
  2. 当我们的计数器达到 3 个项目(即第二个图像)时,我们将强制 wkWebView 取消 decidePolicyFor navigationResponse 委托中的所有导航(即停止加载)。请参阅带有 decisionHandler(.cancel) 的行。这就是阻止崩溃的原因。
  3. 这导致我们收到来自 wkwebview 委托 WebView didFail 导航的回调。此时我们想再次加载我们的 motion/pi url 并再次开始加载过程。
  4. 然后我们必须重置我们的计数器,以便我们可以重复这个过程,直到其他人想出更好的解决方案。

    import UIKit
    import WebKit
    
    class ViewController: UIViewController, WKNavigationDelegate  {
    
        // Memeber variables
        var m_responseCount = 0; /* Counter to keep track of how many loads the webview has done.
                        this is a complete hack to get around the webkit crashing on
                        the second image load */
        let m_urlRequest = URLRequest(url: URL(string: "http://192.168.2.75:6789")!) //Enter your pi ip:motionPort
        var m_webView:WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            m_webView = WKWebView(frame: self.view.frame)  // Create our webview the same size as the viewcontroller
            m_webView.navigationDelegate = self            // Subscribe to the webview navigation delegate
        }
    
        override func viewDidAppear(_ animated: Bool) {
            m_webView.load(m_urlRequest)                    // Load our first request
            self.view.addSubview(m_webView)                 // Add our webview to the view controller view so we can see it
        }
    
        // MARK: - WKNavigation Delegates
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            print("decidePolicyFor navigationAction")
            print(navigationAction.request) //This is the request to connect to the motion/pi server http::/192.168.2.75:6789
            decisionHandler(.allow)
        }
    
        func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
            print("decidePolicyFor navigationResponse")
            print(navigationResponse.response) // This is HTML from the motion/rpi
    
        /* We only want to load the html header and the first image
           Loading the second image is causing the crash
             m_responseCount = 0 - Header
             m_responseCount = 1 - First Image
             m_responseCount >= 2 - Second Image
        */
            if(m_responseCount < 2)
            {
                decisionHandler(.allow)
            }
            else{
                decisionHandler(.cancel) // This leads to webView::didFail Navigation Delegate to be called
            }
    
            m_responseCount += 1;  // Incriment our counter
    
        }
    
        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        /*
         We have forced this failure in webView decidePolicyFor navigationResponse
         by setting decisionHandler(.cancel)
         */
            print("didFail navigation")
    
            m_webView.load(m_urlRequest) //Lets load our webview again
            m_responseCount = 0     /*  We need to reset our counter so we can load the next header and image again
                                    repeating the process forever
                                */
        }
    
        func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        // If you find your wkwebview is still crashing break here for
        // a stack trace
            print("webViewWebContentProcessDidTerminate")
    
        }
    }
    

注意:由于 motion/pi 服务器响应是 http 而不是 https

,因此您还需要将以下内容添加到 info.plist 文件中
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

我鼓励您使用这个基本示例并对其进行修改以满足您的应用程序要求。我也鼓励您 post 自己的任何发现,因为我使用与您完全相同的硬件遇到完全相同的问题,这是一种破解,而不是解决方案。