我需要运行javascript警报的帮助,并在使用xcode创建的简单应用中进行确认,并在其中添加了Webview
我在ViewController.swift中的代码是:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var WebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "MY_URL")
let request = URLRequest(url: url!)
WebView.load(request)
}
}
答案 0 :(得分:1)
首先添加第一件事,
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
第二次在viewDidLoad()
内的代码中添加代码
override func viewDidLoad() {
super.viewDidLoad()
WebView = WKWebView(frame: self.view.frame)
WebView.uiDelegate = self
WebView.navigationDelegate = self
view.addSubview(WebView!)
// your code goes from year
let url = URL(string: "MY_URL")
let request = URLRequest(url: url!)
WebView.load(request)
}
这就是我可以从您的代码中查找的基本信息。
有关更多详细信息,请参见Link,这可能会消除您的所有疑问:D
答案 1 :(得分:1)
我用以下代码解决了问题:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var WebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
WebView = WKWebView(frame: self.view.frame)
WebView.uiDelegate = self
WebView.navigationDelegate = self
view.addSubview(WebView!)
let url = URL(string: "MY_URL")
let request = URLRequest(url: url!)
WebView.load(request)
// Do any additional setup after loading the view, typically from a nib.
}
func webView(_ WebView: WKWebView,
runJavaScriptAlertPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping () -> Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let title = NSLocalizedString("OK", comment: "OK Button")
let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(ok)
present(alert, animated: true)
completionHandler()
}
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: "Cancella", style: .default, handler: { (action) in
completionHandler(false)
}))
self.present(alertController, animated: true, completion: nil)
}
}