Xcode WKWebView代码允许WebView处理弹出窗口



我对Xcode完全陌生,语法完全让我无法理解。

我还有一件事要做,然后我已经在Xcode中实现了我需要做的事情。

我需要插入一个允许WebView处理弹出窗口的函数,但我不知道从哪里开始插入代码。

这是当前代码:

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView()
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html")
let folderPath = Bundle.main.bundlePath
let baseUrl = URL(fileURLWithPath: folderPath, isDirectory: true)
do {
let htmlString = try NSString(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
webView.loadHTMLString(htmlString as String, baseURL: baseUrl)
} catch {
// catch error
}
webView.navigationDelegate = self
view = webView
}
}

我如何编辑它以允许弹出窗口?

请记住,我不知道如何添加我找到的解决方案,所以请告诉我在哪里插入片段。

试试这段代码,希望它能有所帮助!

class ViewController: UIViewController {
var webView: WKWebView!
var popupWebView: WKWebView?
var urlPath: String = "WEBSITE_URL"
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
loadWebView()
}
//MARK: Setting up webView
func setupWebView() {
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
preferences.javaScriptCanOpenWindowsAutomatically = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.uiDelegate = self
webView.navigationDelegate = self
view.addSubview(webView)
}
func loadWebView() {
if let url = URL(string: urlPath) {
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
}
}

}

extension ViewController: WKUIDelegate {
//MARK: Creating new webView for popup
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
popupWebView = WKWebView(frame: view.bounds, configuration: configuration)
popupWebView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
popupWebView!.navigationDelegate = self
popupWebView!.uiDelegate = self
view.addSubview(popupWebView!)
return popupWebView!
}
//MARK: To close popup
func webViewDidClose(_ webView: WKWebView) {
if webView == popupWebView {
popupWebView?.removeFromSuperview()
popupWebView = nil
}
}
}
}

最新更新