有点晚了,但我想添加我的经验以供将来参考。 @Bon Bon 的回答让我走上了解决方案的道路,而我正在尝试使用 Swift 3 和 IOS 10,在这种情况下,代码需要一些修改。
首先你还需要实现WKUIDelegate,所以将它添加到ViewController声明中:
class ViewController: UIViewController, WKUIDelegate {
那么当你实例化WKWebView对象时,例如像这样:
self.webView = WKWebView(frame: self.view.frame)
您还需要为实例的uiDelegate 属性分配正确的值:
self.webView?.uiDelegate = self
那么终于可以使用@Bon Bon提供的代码了,但是注意Swift 3要求的一些小区别,比如presentViewController方法的名字变成present:
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()
}))
self.present(alertController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
self.present(alertController, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let alertController = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)
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)
}))
self.present(alertController, animated: true, completion: nil)
}
这使得alert、confirmation 和text input 在WKWebView 中正常工作,而在Xcode 8 中没有任何编译器警告。我不是专业的 Swift 程序员,因此非常感谢任何关于代码正确性的有用评论。