虽然有点晚了,但我想分享一下我的经验供未来参考。在我尝试使用Swift 3和IOS 10进行编程时,@Bon Bon的答案引导了我找到解决方案,需要对代码进行一些修改。
首先,您需要实现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
和文本输入框
可以在WKWebView
中正常工作,而且在Xcode 8中没有任何编译警告。我并不是一位熟练的Swift程序员,如果对代码的正确性有任何有用的评论,将不胜感激。