Assertion failure in -[UIAlertController addTextFieldWithConfigurationHandler:]

809 views Asked by At

Invoking window.prompt in JavaScript within a WKWebView generates an assertion error:

Assertion failure in -[UIAlertController addTextFieldWithConfigurationHandler:]

The assertion error comes from this WKUIDelegate function:

func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo,
             completionHandler: @escaping (String?) -> Void) {

    let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .actionSheet)

    alertController.addTextField { (textField) in
        textField.text = defaultText
    }

    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
        if let text = alertController.textFields?.first?.text {
            completionHandler(text)
        } else {
            completionHandler(defaultText)
        }
    }))

    alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
        completionHandler(nil)
    }))

    present(alertController, animated: true, completion: nil)
}

The class docs don't show a way to add a configuration handler when adding a text field nor in the initializer. So how are you supposed to handle this?

2

There are 2 answers

1
AshwiniM On

Present should be called from viewController. Is suspect that might be the case with you.

0
Andreas K On

Try changing from style actionSheet to alert. For Objective-C user that would be changing from UIAlertControllerStyleActionSheet to UIAlertControllerStyleAlert.