WKWebView:应用程序因“NSInternalInconsistencyException”异常而崩溃,因为“未调用传递给X的完成处理程序”

时间:2017-12-23 08:55:54

标签: javascript ios wkwebview

尝试在iOS上的WKWebView中同时显示两个JavaScript警告框时,会出现以下异常。该应用程序崩溃了。

  

2017-12-23 00:46:29.434 Couch [3192:3428809] ***终止应用程序   未捕获的异常'NSInternalInconsistencyException',原因:   '完成处理程序传递给 - [XViewController   webView的:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:]   没被称为'

这是有问题的WKWebView委托函数:

func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
             completionHandler: @escaping () -> Void) {

    let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
        completionHandler()
    }))

    if let presenter = alertController.popoverPresentationController {
        presenter.sourceView = self.view
        presenter.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    }
    if presentedViewController == nil {
        present(alertController, animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

在呈现第一个UIAlertController后,presentedViewController不再是nil。然后您的委托方法不会显示第二个/下一个UIAlertController并静默返回。但是,您仍需要拨打completionHandler()

if presentedViewController == nil
{
    // You get here for the second alert box, which is not shown.
    present(alertController, animated: true, completion: nil)
}
else
{
    completionHandler()
}

第二,第三,...... UIAlertController永远不会出现。如果那不是您想要的,请查看here